Nila Vaani
Nila Vaani

Reputation: 213

How to close modal in angular 6

I am trying to close modal from home component.my close button is in home component.If i click close button i want to close modal.If i click close button from home component how to set visible value is false from home component. How can i use service for that? or any other way is there? How do it?

dialog.component.html

    <div [@dialog] *ngIf="visible" class="dialog">
      <ng-content></ng-content>
      <button *ngIf="closable" (click)="close()" aria-label="Close" class="dialog__close-btn">X</button>
      <app-home></app-home>
      </div>
    <div *ngIf="visible" class="overlay" (click)="close()"></div>

home.component.ts:

    <button (click)="showDialog = !showDialog" class="btn">Close</button>

Demo: https://stackblitz.com/edit/angular-7zdnwy?file=src%2Fapp%2Fdialog%2Fdialog.component.html

Upvotes: 0

Views: 2370

Answers (1)

Monster Brain
Monster Brain

Reputation: 2119

I followed this approach from Angular Documentation and it works ok.

You Parent is Dialog and child is app-home. So emitter is defined in child class like this

export class HomeComponent implements OnInit {

  @Output() close = new EventEmitter<boolean>();

  ...

  // <button (click)="onClose()" in html
  onClose() {
    this.close.emit(true)
  }

}

and listen for the event in parent dialog class like this

// html
<app-home (close)="onCloseClick($event)"></app-home>

// Class code
export class DialogComponent implements OnInit {
  ...

  onCloseClick(close: Boolean) {
    if(close){
      this.close()
    }
  }

   ...
}

Hope it helps.

Upvotes: 1

Related Questions