How to select template element by ID in Angular 2 Dart? How to select template element by ID in Angular 2 Dart? dart dart

How to select template element by ID in Angular 2 Dart?


Move the code to ngAfterViewInit()

class MyComponent implements AfterViewInit {  @ViewChild("mapCanvas")  ElementRef canvas;  @override  void ngAfterViewInit() {    DivElement m = canvas.nativeElement;    ...  }}

When the constructor is executed, there is no DOM created yet for the component.

EDIT: Correct but Element was still null. Now works after accessing it in the way of Angular binding with ViewChild annotation.

<div #mapCanvas></div>

update

<div id="my-canvas"></div>
class MyComponent implements AfterViewInit {  ElementRef _elementRef;  MyComponent(this._elementRef);  @override  void ngAfterViewInit() {    var canvas = _elementRef.nativeElement.querySelector("#my-canvas");  }}

update for AngularDart 5

<div id="my-canvas"></div>
class MyComponent implements AfterViewInit {  Element _element;  MyComponent(this._element);  @override  void ngAfterViewInit() {    var canvas = _element.querySelector("#my-canvas");  }}


According to recent discussion in the AngularDart Gitter channel, a good way of doing this in AD5 would be:

@ViewChild(‘someRef’, read: HtmlElement)CanvasElement someRefCanvas;

...or if the setting of the ViewChild happens after the view init (e.g. an *ngIf is involved), you can use a setter:

@ViewChild(‘someRef’, read: HtmlElement)set someRefCanvas(CanvasElement e) {}