3

I would like to know if it is possible in Angular 4 to have two ouput events calling 1 function?

e.g.

<input type="button" value="send" (click, keydown.enter)="doMagic()"/>

instead of doing

<input type="button" value="send" (click)="doMagic()" (keydown.enter)="doMagic()"/>

@HostListener is not an option.

Thanks for your help!

2 Answers 2

4

It doesn't seem so - at least not from this issue asking for it as a feature: https://github.com/angular/angular/issues/6675

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer! Very sad they dont want to implement this in near future. Would be essential for clean coding!
If you really need it there's this: medium.com/@TheLarkInn/… but it does mean implementing it yourself.
2

Alternative solution - may be worth considering.

template:

<input #send type="button" value="send" />

component:

@ViewChild('send') sendElement: ElementRef;
sub: Subscription;
ngAfterViewInit() {
     this.sub = Observable.fromEvent('click', this.sendElement)
        .merge(Observable.fromEvent('keydown.enter', this.sendElement))
        .map(t=> this.doMagic()).subscribe();
}

ngOnDestroy() {
  this.sub.unsubscribe();
}

doMagic() {
  ...
}

2 Comments

thanks for your answer. it is a good alternative but unfortunately too much code :-(
@dspies add your new code as a new answer rather than editing an existing answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.