Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

Tags:

angular

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?

like image 944
yavg Avatar asked Feb 11 '19 06:02

yavg


1 Answers

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)
}
like image 183
zmag Avatar answered Sep 21 '22 13:09

zmag