Angular 4 - Execute function only when the variable is changed

0

I need to run a function, but it can only run if the variable is set to false.

What context: When pressing TAB the system calls the function (fnTab). This function performs a search in the database and prints the description in the input. However, if the user is very quick in the tab click, it will print the input description of the next record and not the current one.

    
asked by anonymous 24.10.2017 / 15:40

1 answer

0

You can call this method using the "change" event of the input element, so when the variable (in this case the input content) is changed, the method is called.Ex.:

<input type="text" [(ngModel)]="suaVariavel" (change)="seuMetodo($event)" />

Remember that if you intend to change the value of this variable through the code, the above line will generate an infinite loop, since both ngModel and its method will be trying to change the same variable, if this is the case, it is better to use the alternative below:

<input type="text" [ngModel]="suaVariavel" (ngModelChange)="seuMetodo($event)" />

Note that when you use (change), the method call will only occur when the field loses focus, but the method is called with the correct field information.

    
01.12.2017 / 20:48