Search code examples
angularmaterial-design-liteangular2-mdl

EventEmitter in custom dialog component


I've got a custom dialog component and instead of using a service inside of the dialog component I want to use an event emitter and subscribe to that in the parent component.

Is that something that's possible?


Solution

  • With version 2.0.0 of angular2-mdl it is possible. Here is a working plnkr that demonstrates how this works: http://plnkr.co/edit/MSBlJm2ZKtTvMSgf27Yd?p=preview

    You need to create a regular component:

    @Component({
      selector: 'dialog-content',
      templateUrl: 'dialog-content.component.html'
    })
    export class DialogContentComponent {
    
      @Output() emitter = new EventEmitter();
      @Input() dialog: MdlDialogComponent;
    
      // or this way: constructor(private dialog: MdlDialogComponent){}
    
      fireEvent() {
        this.emitter.emit(1);
      }
    
      closeDialog() {
        this.dialog.close();
      }
    }
    

    The html looks like following:

    <p>
      <button 
          mdl-button  
          mdl-button-type="raised" 
          mdl-colored="primary" 
          mdl-ripple
          (click)="fireEvent()">Fire event</button>
    
      <button 
          mdl-button 
          mdl-button-type="raised" 
          mdl-colored="accent"
          mdl-ripple
          (click)="closeDialog()">Close dialog </button>
    </p>
    

    As you can see there are two buttons. One fires the number 1 every time the button is clicked. The other button closes the dialog.

    Now the interesting part: how to use this. You need to create an embedded mdl-dialog with your component as the content:

       <button 
          mdl-button 
          mdl-button-type="raised" 
          mdl-colored="primary"
          mdl-ripple
          (click)="testDialog.show()">Open dialog</button>
    
        Counter: {{counter}}
    
        <mdl-dialog #testDialog>
          <dialog-content [dialog]="testDialog" (emitter)="onEmitting($event)"></dialog-content>
       </mdl-dialog>
    

    The mdl-dialog is referenced by the testDialog constant and an emitter is registered. If you click the button the dialog will be shown. If you click the "Fire event"-button the event is catched by the outer component and a counter is incremented to demonstrate that it works. Here is a screenshot:

    mdl-dialog screenshot