我只能从父视图的HTML中调用子组件中包含的模式,而不是父组件中的HTML,为什么? [英] I can call a modal in contained in a child component ONLY from the HTML of the view of the parent, not in the component of the father, why?
问题描述
我有一个组件,该组件又嵌入了一个子组件.基本上从父组件中,我将调用包含在子组件中的模式.只需点击父亲的HTML即可.
I have a component that in turn has embedded a child component. basically from the parent component I call a modal that is contained in the child component. and this works perfectly with a click from the father's HTML.:
<a type="button" (click)="modal.show()" >
在HTML父级中
<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">
.
.
.
在 son组件.ts
var1:any;
var2:any;
var3:any;
@ViewChild(mymodal) mymodal;
... // other code
public show() {
this.mymodal.show(); //call a modal
}
,但是如果我直接从组件中调用它,这将不起作用.我还想修改父组件中在子组件中定义的变量的值,反之亦然.
but this does not work if I call it directly from the component. I would also like to modify the value of the variables that I have defined in the child component, from the parent component and vice versa.
在父组件
@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)
}
为什么会这样?
推荐答案
您在父组件中引用了错误的变量.
You referenced a wrong variable in parent component.
首先,您需要引用son
组件的模板变量,该模板变量是modal
.
First, you need to reference a template variable of son
component which is modal
.
@ViewChild('modal') modal: any;
然后,在父组件中引用modal
的mymodal
属性.
And then, reference a mymodal
property of modal
in parent component.
ngOnInit(){
setTimeout(()=>{
this.modal.mymodal.show();
this.modal.var1=1;
this.modal.var2=2;
this.modal.var3=3;
},5000)
}
这篇关于我只能从父视图的HTML中调用子组件中包含的模式,而不是父组件中的HTML,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!