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()" >
in HTML Parent
<a type="button" (click)="modal.show()">
open modal
</a>
<son #modal ></son>
In HTML son
<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">
.
.
.
In son component .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.
In 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)
}
Why does this happen?
You referenced a wrong variable in parent component.
First, you need to reference a template variable of son
component which is modal
.
@ViewChild('modal') modal: any;
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With