Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect change in model for input field from directive in angular2

Tags:

angular

I have this code for a textarea, it is working great with the ngModel and updating live, however i would like my-custom-directive to know when the model bound to this textarea is changing.

How can i detect a model change for this textarea in the my-custom-directive?

  <textarea my-custom-directive class="green" [(ngModel)]="customertext"></textarea>
like image 319
B Hull Avatar asked Jan 31 '16 10:01

B Hull


People also ask

How do I detect a text input change event with angular?

When we enter tags one character at a time, Angular performs change detection after every character is entered. So, if we type in “foo”, the Angular binding records for the <input> element value attribute will follow this sequence: "" , "f" , "fo" , "foo" .

What are the directives in angular?

In Angular, Directives are defined as classes that can add new behavior to the elements in the template or modify existing behavior. The purpose of Directives in Angular is to maneuver the DOM, be it by adding new elements to DOM or removing elements and even changing the appearance of the DOM elements.


2 Answers

Update

@Directive({
  selector: 'xyz', 
  host: {'(ngModelChange)': 'doSomething($event)'}  
}) 
export class Xyz {
  doSomething(event){... }  
} 

Original

<textarea my-custom-directive class="green" [(ngModel)]="customertext"
    (ngModelChange)="doSomething($event) "></textarea>
[(ngModel)]="customertext"

is the short form of

[ngModel]="customertext" (ngModelChange)="customertext=$event"  
like image 62
Günter Zöchbauer Avatar answered Oct 15 '22 22:10

Günter Zöchbauer


try add to your directive:

@HostListener('input') onInput() {
        console.log('on input');
}
like image 37
Robert Gurgul Avatar answered Oct 15 '22 23:10

Robert Gurgul