Jonathan Applebaum
Jonathan Applebaum

Reputation: 5986

how to neatly reference multiple angular event handlers to html elements

I am very new to angular2 and i was wondering if there is a shorter way to write the keypress and paste events so that the html code will be more readable (i am using Type Script):

 <textarea rows="1" class="txt" (keypress)="c()" (paste)="c()" [(ngModel)]="LeftText"></textarea>

Upvotes: 1

Views: 2706

Answers (1)

Estus Flask
Estus Flask

Reputation: 222309

When HTML template becomes cluttered with Angular logic, this means that logic should be moved to directive/component classes.

In this case this can be a directive:

@Directive({  selector: '[modify]' })
class ModifyDirective  {
  @Input() modify;

  @HostListener('paste', ['$event.target'])
  @HostListener('keypress', ['$event.target'])
  onModify(e) {
    if (this.modify) {
      this.modify(e);
    }
  }
}

Which is used like

<textarea [modify]="c">

Notice that c is passed to the directive as a callback, this means that a method should be bound to the context in order to keep proper this.

Upvotes: 4

Related Questions