我有一个组件,反过来嵌入了一个子组件.基本上从父组件我调用子组件中包含的模态.这与父亲的HTML点击完美配合:
<a type="button" (click)="modal.show()" >
Run Code Online (Sandbox Code Playgroud)
在HTML Parent中
<a type="button" (click)="modal.show()">
open modal
</a>
<son #modal ></son>
Run Code Online (Sandbox Code Playgroud)
在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">
.
.
.
Run Code Online (Sandbox Code Playgroud)
在儿子组件.ts
var1:any;
var2:any;
var3:any;
@ViewChild(mymodal) mymodal;
... // other code
public show() {
this.mymodal.show(); //call a modal
}
Run Code Online (Sandbox Code Playgroud)
但如果我直接从组件中调用它,这不起作用.我还想修改我在子组件中定义的变量的值,从父组件修改,反之亦然.
在PARENT COMPONENT中
@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)
}
Run Code Online (Sandbox Code Playgroud)
为什么会这样?
您在父组件中引用了错误的变量。
首先,您需要引用son组件的模板变量,即modal.
@ViewChild('modal') modal: any;
Run Code Online (Sandbox Code Playgroud)
然后,引用父组件中mymodal的属性。modal
ngOnInit(){
setTimeout(()=>{
this.modal.mymodal.show();
this.modal.var1=1;
this.modal.var2=2;
this.modal.var3=3;
},5000)
}
Run Code Online (Sandbox Code Playgroud)