Relaular和Dart的新手我有以下问题:
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>
据我所知,问题是querySelector
只查询基本dom而不是shadowDom 。
但是,如何在模板中查询ID?
答案 0 :(得分:8)
将代码移至ngAfterViewInit()
class MyComponent implements AfterViewInit {
@ViewChild("mapCanvas")
ElementRef canvas;
@override
void ngAfterViewInit() {
DivElement m = canvas.nativeElement;
...
}
}
执行构造函数时,尚未为组件创建DOM。
编辑:正确但元素仍为空。现在可以在使用ViewChild注释进行Angular绑定的方式访问它之后工作。
<div #mapCanvas></div>
<强>更新强>
<div id="my-canvas"></div>
class MyComponent implements AfterViewInit {
ElementRef _elementRef;
MyComponent(this._elementRef);
@override
void ngAfterViewInit() {
var canvas = _elementRef.nativeElement.querySelector("#my-canvas");
}
}
更新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");
}
}
答案 1 :(得分:0)
根据AngularDart Gitter频道中最近的讨论,在AD5中执行此操作的一种好方法是:
@ViewChild(‘someRef’, read: HtmlElement)
CanvasElement someRefCanvas;
...或者如果ViewChild的设置发生在视图初始化之后(例如,涉及到* ngIf),则可以使用setter:
@ViewChild(‘someRef’, read: HtmlElement)
set someRefCanvas(CanvasElement e) {
}