gpt4 book ai didi

Angular2 - NgSwitch 中的模板引用

转载 作者:太空狗 更新时间:2023-10-29 18:17:06 26 4
gpt4 key购买 nike

我有一个 NgSwitch 模板。在 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 个组件实现的接口(interface)上)。问题是 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 的情况下)。

最佳答案

如果您在 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;
...

Then ref 在调用构造函数时尚未设置。甚至不在 init 上。仅在 View 初始化之后。

这样,使用以下组件:

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 .

关于Angular2 - NgSwitch 中的模板引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38674651/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com