Search code examples
javascriptangulartypescriptcallbackangular-event-emitter

Angular EventEmitter with Callback


I want to make the custom button component in my angular application and i have a method to implement click, here is the code:

export class MyButtonComponent {
  @Input() active: boolean = false;
  @Output() btnClick: EventEmitter<MouseEvent> = new EventEmitter<MouseEvent>();

  @HostListener('click', ['$event'])
  public async onClick(event: MouseEvent) {
      this.active = true;
      await this.btnClick.emit(event);
      this.active = false;
  }
}

the problem is when user clicks the button the 'active' will be true and event will execute, but the 'active' will be false without waiting the event finish.I want the 'active' to false when the event is fully executed.

how can i fix this or how can i add Callback to the emit method?


Solution

  • You can subscribe to EventEmitters:

    this.btnClick.subscribe(() => this.active = false);

    That would give you

    export class MyButtonComponent implements OnInit {
      @Input() active: boolean = false;
      @Output() btnClick: EventEmitter<MouseEvent> = new EventEmitter<MouseEvent>();
    
      @HostListener('click', ['$event'])
      public onClick(event: MouseEvent) {
          this.active = true;
          this.btnClick.emit(event);
      }
      
      ngOnInit() {
        this.btnClick.subscribe(() => this.active = false);
      }
    }