Function running before receiving value in ngModel

Asked

Viewed 47 times

0

I have the following checkbox:

<mat-checkbox [(ngModel)]="anuncio.checkouCarimbo" (click)="checkouAnuncio()" name="checksegundoAnuncio"
    class="example-margin checkFoto">
</mat-checkbox>

Function called by checkbox when clicked:

  checkouAnuncio(){
    for(let i=0;i<this.anuncios.length;i++){
      if(this.anuncios[i].checkouCarimbo == true){
        this.habilitaCarimbar = true;
        return;
      }else{
        this.habilitaCarimbar = false;
      }
    }
  }

My goal is to go through the advertising array and if at some position the checkouCarimbo is true, set this.enable fieldCarimbar, but when clicking is called the function and only then is set in ngModel, so my logic is broken. Is there any way to receive the value first and then perform the function or follow that order?

  • You should listen to the change over click event

1 answer

1


Hello,

I created a test in Stackblitz: https://stackblitz.com/edit/angular-sak5da

In the template (click)="checkouAnuncio()" passes the ad by clicking and no longer uses ngModel:

`<mat-checkbox [checked]="anuncio.checkouCarimbo" (click)="checkouAnuncio(anuncio)" name="checksegundoAnuncio" class="example margin checkFoto"> </mat-checkbox>`

In TS, the function modifies the checkbox value:

checkouAnuncio(checkboxClicked){
      checkboxClicked.checkouCarimbo = !checkboxClicked.checkouCarimbo;

      for(let i=0;i<this.anuncios.length;i++){
         if(this.anuncios[i].checkouCarimbo == true){
         this.habilitaCarimbar = true;
         return;
         }else{
           this.habilitaCarimbar = false;
         }
      }
  }

I made a modification in the function, it is up to you to use it because its function is also correct, follows:

checkouAnuncio(checkboxClicked){
      checkboxClicked.checkouCarimbo = !checkboxClicked.checkouCarimbo;
      this.habilitaCarimbar = this.anuncios.filter(anuncio=>anuncio.checkouCarimbo).length > 0;
  }
  • It’s not what I need. habilitaCarimbar should be true if at least one ad has the ad.checkouCarimbo true. And it is through ngModel that the true/false of this checkbox is exchanged

  • Is your problem in order only? You want me to run the function before the checkbox is "checked"?

  • The function is running before it is enabled, then the enable variableCarimbar is false,

  • See if this is what you need now, I modified the answer by adding a link to a demo

  • I’ll try when I get a chance and I’ll get back to you

Browser other questions tagged

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