4

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?

Mohammad Abbasi
  • 302
  • 4
  • 10

2 Answers2

1

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);
  }
}
Alex
  • 1,090
  • 7
  • 21
  • 3
    Why is this the accepted answer? This is not working for me, the subscribe still executes before the emit. – Simon Lapointe Nov 12 '19 at 23:02
  • You can filter on the EventEmitter content: ``` this.btnClick.pipe(filter(event => !!event)).subscribe(() => this.active = false); ``` – Alex Jul 28 '20 at 14:01
0

Since the Active is an Input why not change it's value from the parent component. I mean you can move this.active = false; from MyButtonComponent to your HostComponent inside the method that handle your Output

ilyas shabi
  • 194
  • 1
  • 7