Function being executed before receiving the value in ngModel

0

I have the following checkbox:

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

The function called by the checkbox when it is 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 ads array and if at any position check it, it is true, set the this.disable_value field, but clicking the function is called and then it is set to ngModel, so my logic is broken. Is there any way to get the value first and then run the function or follow that order anyway?

    
asked by anonymous 23.11.2018 / 11:20

1 answer

1

Hello,

I created a test on StackBlitz: link

In the template (click)="checkouAnuncio()" passes the ad when 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 value of the checkbox:

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 change in the function, it is at your discretion to use it because its function is also correct, it follows:

checkouAnuncio(checkboxClicked){
      checkboxClicked.checkouCarimbo = !checkboxClicked.checkouCarimbo;
      this.habilitaCarimbar = this.anuncios.filter(anuncio=>anuncio.checkouCarimbo).length > 0;
  }
    
23.11.2018 / 12:00