2016-07-30 70 views
2

我有一個NgSwitch模板。在NgSwitch中,我想獲得一個對初始化模板的模板引用。是這樣的:Angular2 - NgSwitch中的模板引用

<div class="container" [ngSwitch]="model.type"> 
     <first-component #ref *ngSwitchCase="0"></first-component> 
     <second-component #ref *ngSwitchCase="1"></second-component> 
     <third-component #ref *ngSwitchCase="2"></third-component> 
    </div> 

當我想調用的初始化部件(第一/第二/第三次)的方法(其中,所有這3個部件實現一個接口上定義的)該組件上的按鈕點擊。問題是ViewChild未定義。如果我#REF移動到容器的div,像這樣:

<div class="container" #ref [ngSwitch]="model.type"> 
    <first-component *ngSwitchCase="0"></first-component> 
    <second-component *ngSwitchCase="1"></second-component> 
    <third-component *ngSwitchCase="2"></third-component> 
</div> 

的ViewChild(模板參考)被初始化,但然後我可以調用該組件的方法。

如何使用NgSwitch指令和模板引用變量? 另一方面,如何從其父級調用初始化組件(在將#ref移動到容器div的情況下)。

回答

2

,如果你在ngSwitchCase使用模板參考變量,它的工作原理,是這樣的:

<div class="container" [ngSwitch]="model.type"> 
    <first-component #ref *ngSwitchCase="0"></first-component> 
    <second-component #ref *ngSwitchCase="1"></second-component> 
    <third-component #ref *ngSwitchCase="2"></third-component> 
</div> 

注意,如果你有,:

export class SomeComponent { 

    @ViewChild('ref') ref; 
... 

然後ref尚未設置在當構造函數被調用。甚至沒有在初始化。只有在查看init之後。

通過這種方式,具有下列組分:

export class AppComponent implements OnInit, AfterViewInit { 
    model = {type: 0}; 

    @ViewChild('ref') ref; 

    constructor() { 
    console.log('constructor:', this.ref); 
    } 
    ngOnInit() { 
    console.log('ngOnInit:', this.ref); 
    } 
    ngAfterViewInit() { 
    console.log('AfterViewInit:', this.ref); 
    } 

} 

的輸出是:

constructor: undefined 
ngOnInit: undefined 
AfterViewInit: FirstComponent {...} 

參見demo plunker here

+0

謝謝你的答案。我發現我的模板中存在這個問題。我使用ngSwitchCase綁定到枚舉變量,如下所述http://stackoverflow.com/questions/35835984/how-to-use-a-typescript-enum-value-in-an-angular2-ngswitch-statement - 如果我使用這個即使在初始化視圖後,視圖子項也是未定義的枚舉模式。當我切換到綁定數字的ng-switch時 - 就像我爲了簡化它的代碼所做的那樣。你有什麼想法爲什麼它可能發生在枚舉綁定? – galvan

0

模板引用變量不應與結構指令一起使用。這裏解釋一個原因:Thomas Hilzendegen's blog

我的解決方案是爲使用[ngSwitch]的容器標記創建一個模板引用變量,然後使用它的children屬性訪問它的子節點。例如

<div [ngSwitch]="..." [class.error] = "(elem.children.item(0).className.indexOf('someClass') !== -1" #elem> 
... 
</div>