skip to Main Content

In my Angular app I have a home (parent) component that I’m displaying a modal in:

<button>
    New message
</button>

<app-modal modalTitle="New message">
  <p>
    Lorem ipsum dolor sit, amet consectetur adipisicing elit. Nam nihil
    dignissimos cumque provident eius id magnam blanditiis saepe. Reiciendis
    inventore nihil modi eveniet laborum quidem quo labore minima porro?
    Laudantium.
  </p>
  <div modalFooter>
    <button>Custom button</button>
  </div>
</app-modal>

The modal component is:

<dialog #modal class="max-w-screen-xl border rounded-t-lg">
<button (click)="modal.close()">
rest of markup....
</dialog>

When clicking the New message button in the parent component, I want to call the openModal() method on the <dialog> element in the modal component.

I have tried using an EventEmitter and Output but it didn’t work.

What is the common way to do something like this in Angular?

2

Answers


  1. I guess one of approaches is:

    In your parent component.ts:

    ...
    isShowModalInChildComponent = false;
    
    openModalWindowInChildComponent(): void {
      isShowModalInChildComponent = true;
    }
    ...
    

    In your parent component.html:

    ...
    <button (click)="openModalWindowInChildComponent()">
        New message
    </button>
    
    <app-modal 
      [isShowDialog]="isShowModalInChildComponent"
      modalTitle="New message"
    >
      ...
    </app-modal>
    

    In your modal component.ts:

    @Input('isShowDialog')
    set _isShowDialog(data: boolean) {
      this.isShowDialog = data;
    }
    isShowDialog = false;
    

    In your modal component.html:

    <dialog 
      #modal 
      *ngIf="isShowDialog"
      class="max-w-screen-xl border rounded-t-lg"
    >
      <button (click)="modal.close()">
      rest of markup....
    </dialog>
    
    Login or Signup to reply.
  2. I have done native HTML dialogs in Angular apps for a bit. My approach is usually something like this:

    my-component.html

    <button (click)="open()"> Open Dialog </button>
    
    <dialog #mydialog>
      <p>
        Some text here
      </p>
      <button (click)="close()"> Close Dialog </button>
    </dialog>
    

    my-component.ts

    class MyComponent {
      @ViewChild('mydialog') myDialog: HTMLElement;
    
      open() {
        this.myDialog.nativeElement.showModal()
      }
    
      close() {
        this.myDialog.nativeElement.close()
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search