Angular 4 - Perform function only when variable is changed

Asked

Viewed 2,461 times

0

I need to execute a function, but it can only run if the variable is 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 too quick to click the tab, he will print the description of the next entry and not in the current one.

  • What code do you have to show us?

1 answer

0


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

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

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

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.