Search code examples
angularangular-materialangular-material2

Trigger another button click from md-button Angular Material


I have a page (say a parent page) that contain MdDialog component. Inside the dialog window, I have set a md-button. Can this md-button trigger the parent page button's function on click?


Solution

  • Yes, you can use a subject to trigger an event. Use a shared service for emitting and subscribing to the subject.

    Define a shared.service like this:

    import {Injectable } from '@angular/core';
    import { Subject } from 'rxjs';
    
    @Injectable()
    export class SharedService{
       public triggerParentMethod: Subject<boolean> = new Subject<boolean>();
    }
    

    In your ParentComponent, subscribe to the triggerParentMethod in constructor:

    constructor(private sharedService:SharedService,public dialog: MdDialog){
          this.sharedService.triggerParentMethod.subscribe( value =>{
            if(value == true){
              // Call some method here or some piece of code
              console.log('called from dialog');
            }
          });
        }
    

    Emit triggerParentMethod from your dialog:

    this.sharedService.triggerParentMethod.next(true);  
    

    Complete working demo.