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

20.7k views Asked by At

Relativley new to Angular and Dart I have the following problem:

my_component.dart:

import 'package:angular2/core.dart';
import 'package:angular2_components/angular2_components.dart';

import 'package:google_maps/google_maps.dart';
import 'dart:html';


@Component(
  selector: 'google-route-map',
  styleUrls: const ['my_component.css'],
  templateUrl: 'my_component.html',
  directives: const [materialDirectives],
  providers: const [materialProviders],
)
class MyComponent {

  MyComponent() {

    var m = querySelector("#my-canvas");

    print (m); // is null

    // do something with m....
  }
}

my_component.html:

<div id="my-canvas"></div>

As far as I have understood the problem is that querySelector queries only the base dom not the shadowDom.

However how do I simply query an id within my template?

2

There are 2 answers

1
Günter Zöchbauer On BEST ANSWER

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");

  }
}
0
DanielMcQ On

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) {

}