gal*_*van 5 ng-switch angular2-template angular
我有一个 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>
Run Code Online (Sandbox Code Playgroud)
当单击组件中的按钮时,我想调用初始化组件(第一/第二/第三)的方法(该方法在所有这三个组件实现的接口上定义)。问题是 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>
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
请注意,如果您有:
export class SomeComponent {
@ViewChild('ref') ref;
...
Run Code Online (Sandbox Code Playgroud)
然后ref在调用构造函数时尚未设置。甚至在初始化时也没有。仅在视图初始化之后。
这样,具有以下组件:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
输出是:
constructor: undefined
ngOnInit: undefined
AfterViewInit: FirstComponent {...}
Run Code Online (Sandbox Code Playgroud)
请参阅此处的演示 plunker。
| 归档时间: |
|
| 查看次数: |
5474 次 |
| 最近记录: |