简体   繁体   中英

Close modal from the parent component

So I've got this parent component, let's call it List, which has property addModal: boolean; and a

<button 
    (click)="addModal = true">
    Show Modal
</button>

in the template, which shows the modal component normally on click, which looks like this:

<app-modal *ngIf="addModal"></app-modal>

The app-modal is a separate component, and I would like to be able to close the modal from within it. As I'm learning Angular, I understood that it can be done with the EventEmitter . I got stuck at this point, this is what I've got now, but can't figure out how to listen for that close event... This is how the Modal component looks like:

@Output() addModal = new EventEmitter();

decline() {
   this.addModal.emit(true);  //?  console logs the EventEmitter object
}

in the Modal template:

<button (click)="decline()"></button>

I know that I should catch that in the parent component, but can't figure it out exactly...

Any help much appreciated

You can listen for emitted events on the host element where $event is the emitted value, in your case true :

<app-modal *ngIf="addModal" (addModal)="doSomething($event)"></app-modal>

As a general tip, the name addModal is not really a good name because it doesn't explain the event. Consider changing it to something like declined instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM