2017-03-02 44 views
1

我有一個angular2組件爲其模板是這樣的:ViewChildren爲NG-模板

<div> 
    <div><ng-template #left></ng-template></div> 
    <div><ng-template #right></ng-template></div> 
</div> 

我想能夠使用ViewChildren檢索到所有ng-template元素的引用,但我不知道的我需要在括號之間傳遞類型。

回答

2
@ViewChildren(TemplateRef) templates: QueryList<TemplateRef>; 

ngAfterViewInit() { 
    console.log(this.templates.toArray()); 
} 

@ViewChild('left') left:TemplateRef; 
@ViewChild('right') right:TemplateRef; 

ngAfterViewInit() { 
    console.log(this.left, this.right); 
} 
+1

嘿,我剛剛寫[一對DOM操作的文章(https://medium.com/@maximus.koretskyi/exploring-angular-dom-abstractions- 80b3ebcfc02#.lc9ev4gg0!)使用'ViewContainerRef',看看你是否有時間。 –

+2

關於丟失泛型的視覺工作室代碼投訴:'[ts]泛型類型'TemplateRef '需要1個類型參數'我不知道,不應該是'ElementRef'? – bvdb

+0

我無法看到泛型參數將實現什麼作用。 'TemplateRef '應該做恕我直言。 –