Search code examples
angulardartdart-htmlangular2-dart

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


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?


Solution

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