我有一个组件,它又嵌入了一个子组件。基本上,我从父组件调用子组件中包含的模态。只要点击一下父亲的HTML,这个功能就可以完美地工作
<a type="button" (click)="modal.show()" >
<a type="button" (click)="modal.show()">
open modal
</a>
<son #modal ></son>
在
HTML儿子
<div mdbModal #mymodal="mdbModal" class="modal fade" id="mymodal" tabindex="-1" role="dialog"
aria-labelledby="mymodal" aria-hidden="true" [config]="{backdrop: true, ignoreBackdropClick: false}">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
.
.
.
在
子组件.ts
var1:any;
var2:any;
var3:any;
@ViewChild(mymodal) mymodal;
... // other code
public show() {
this.mymodal.show(); //call a modal
}
在
父组件
@ViewChild('mymodal') mymodal: any;
.
.
ngOnInit() {
setTimeout(() => {
this.mymodal.show(); // Uncaught (in promise): TypeError: Cannot read property 'show' of undefined
this.mymodal.var1=1;
this.mymodal.var2=2;
this.mymodal.var3=3;
}, 5000)
}
为什么会这样?