Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 566
Mohammad Abbasi Avatar asked Dec 19 '25 23:12

Mohammad Abbasi


1 Answers

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);
  }
}
like image 57
Alex Avatar answered Dec 22 '25 12:12

Alex