Angular2:从模板访问子节点
Angular2: Accessing child nodes from a template
我有一个组件,我想从模板访问一些子节点。我实现了访问 details
div,但我不知道代码为何有效。 Future class
究竟是什么?为什么第一行打印 null?这是从模板访问子节点的正确方法吗?
@Component(selector: 'hero-detail', template: '<div #details></div>')
class HeroDetailComponent implements OnInit {
Hero hero;
@ViewChild('details')
var details;
Future ngOnInit() async {
// why this command prints null?
print(details);
// why this command prints "Instance of 'ElementRef_'"
new Future(() => print(details));
}
}
@Component(selector: 'hero-detail', template: '<div #details></div>')
class HeroDetailComponent implements OnInit {
Hero hero;
// Angular generates additional code that looks up the element
// from the template that has a template variable `#details
// and assigns it to `var details`
@ViewChild('details')
var details;
// I don't think Future does anything here.
Future ngOnInit() async {
// why this command prints null?
// this is too early. `@ViewChild()` is only set in `ngAfterViewInit`
// at this point the view is not yet fully created and therefore
// `#details can't have been looked up yet
print(details);
// why this command prints "Instance of 'ElementRef_'"
// this delays `print(details)` until the next Dart event loop
// and `details` is then already lookup up and assigned
new Future(() => print(details));
}
// this is the right place
// needs `class HeroDetailComponent implements OnInit, AfterViewInit {
ngAfterViewInit() {
print(details);
}
}
我有一个组件,我想从模板访问一些子节点。我实现了访问 details
div,但我不知道代码为何有效。 Future class
究竟是什么?为什么第一行打印 null?这是从模板访问子节点的正确方法吗?
@Component(selector: 'hero-detail', template: '<div #details></div>')
class HeroDetailComponent implements OnInit {
Hero hero;
@ViewChild('details')
var details;
Future ngOnInit() async {
// why this command prints null?
print(details);
// why this command prints "Instance of 'ElementRef_'"
new Future(() => print(details));
}
}
@Component(selector: 'hero-detail', template: '<div #details></div>')
class HeroDetailComponent implements OnInit {
Hero hero;
// Angular generates additional code that looks up the element
// from the template that has a template variable `#details
// and assigns it to `var details`
@ViewChild('details')
var details;
// I don't think Future does anything here.
Future ngOnInit() async {
// why this command prints null?
// this is too early. `@ViewChild()` is only set in `ngAfterViewInit`
// at this point the view is not yet fully created and therefore
// `#details can't have been looked up yet
print(details);
// why this command prints "Instance of 'ElementRef_'"
// this delays `print(details)` until the next Dart event loop
// and `details` is then already lookup up and assigned
new Future(() => print(details));
}
// this is the right place
// needs `class HeroDetailComponent implements OnInit, AfterViewInit {
ngAfterViewInit() {
print(details);
}
}