1

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>
2

1 Answer 1

4

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.

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

Comments

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.