Angular2-NgSwitch内的模板参考 [英] Angular2 - Template reference inside NgSwitch
问题描述
我有一个NgSwitch模板.在NgSwitch中,我想获得对初始化模板的模板引用.像这样:
I have a NgSwitch template. In the NgSwitch I want to get a template reference to the initialized template. Something like this:
<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>
当单击组件中的按钮时,我想调用方法(在这三个组件实现的接口上定义)的已初始化组件(第一/第二/第三).问题是ViewChild未定义.如果我将#ref移到容器div上,像这样:
When clicking on a button in the component I want to call to the initialized component (first/second/third) to a method (which defined on an interface that all these 3 component implement). The problem is the ViewChild is undefined. If I move #ref to the container div, like this:
<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(模板引用)已初始化,但随后我可以调用组件的方法.
The ViewChild (template reference) is initialized but then I can call the method of the component.
如何同时使用NgSwitch指令和模板引用变量? 或者,另一方面,如何从其父级调用已初始化的组件(在这种情况下,我将#ref移至容器div).
How can I use both NgSwitch directive and template reference variable? Or on the other hand, how can I call the initialized component from its parent (in a case I move the #ref to the container div).
推荐答案
如果您在ngSwitchCase
处使用模板引用变量,则可以使用以下方式:
It works if you use a template reference variable at the ngSwitchCase
, this way:
<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之后.
Then ref
is not yet set at when the constructor is called. Not even on init. Only after view init.
这种方式,具有以下组成部分:
This way, with the following component:
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 {...}
这篇关于Angular2-NgSwitch内的模板参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!