I\'m trying to access a native element in order to focus on it when another element is clicked (much like the html attribute \"for\" - for cannot be used on elements of th
Initializing the Canvas like below works for TypeScript/Angular solutions.
const canvas = <HTMLCanvasElement> document.getElementById("htmlElemId");
const context = canvas.getContext("2d");
You'll also get this error if your target element is inside a hidden element. If this is your HTML:
<div *ngIf="false">
<span #sp>Hello World</span>
</div>
Your @ViewChild('sp') sp
will be undefined.
In such a case, then don't use *ngIf
.
Instead use a class to show/hide your element being hidden.
<div [class.show]="shouldShow">...</div>
@ViewChild('keywords-input') keywordsInput;
doesn't match id="keywords-input"
id="keywords-input"
should be instead a template variable:
#keywordsInput
Note that camel case should be used, since -
is not allowed in template reference names.
@ViewChild()
supports names of template variables as string:
@ViewChild('keywordsInput') keywordsInput;
or component or directive types:
@ViewChild(MyKeywordsInputComponent) keywordsInput;
See also https://stackoverflow.com/a/35209681/217408
Hint:
keywordsInput
is not set before ngAfterViewInit()
is called
it just simple :import this directory
import {Component, Directive, Input, ViewChild} from '@angular/core';
What happens is when these elements are called before the DOM is loaded these kind of errors come up. Always use:
window.onload = function(){
this.keywordsInput.nativeElement.focus();
}
The accepted answer is correct in all means and I stumbled upon this thread after I couldn't get the Google Map render in one of my app components.
Now, if you are on a recent angular version i.e. 7+ of angular then you will have to deal with the following ViewChild declaration i.e.
@ViewChild(selector: string | Function | Type<any>, opts: {
read?: any;
static: boolean;
})
Now, the interesting part is the static value, which by definition says
Now for rendering a map, I used the following ,
@ViewChild('map', { static: true }) mapElement: any;
map: google.maps.Map;