2016-03-12 65 views
0

我有一个组件,我想从模板中访问一些子节点。我达到了访问details股利,但我不知道为什么代码的作品。 Future class究竟是什么?为什么第一行输出为空?这是从模板访问子节点的正确方法吗?Angular2:从模板访问子节点

@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)); 
    } 
} 
+0

我不知道,但镖似乎是几个错误1.'英雄好汉;'应该是'英雄:英雄;在angular2'2.我们不能给名字的生命周期挂钩喜欢你'未来的ngOnInit()',并尝试''新'未来...'后打印(详细)'' –

回答

4
@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); 
    } 
} 
+0

谢谢,它的工作。只需注意:类必须实现AfterViewInit类。 – Cequiel

+0

是的,它在'ngAfterViewInit()'之前的行中提到。如果这样可以解决你的问题,你能否接受它来表明问题已经回答。 –