2016-03-12 63 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()'之前的行中提到。如果這樣可以解決你的問題,你能否接受它來表明問題已經回答。 –