mat-checkbox check only if condition is true

12,702

I have used event binding on ngModel in the html and also modified some code in app.component.ts. Now only the checkbox with id 2 can be checked. Please see the code below

in app.component.html

<mat-checkbox (ngModel)="canbeChecked(user.id)" (click)="userSelectClick(user.id)"></mat-checkbox>

and in app.component.ts

export class AppComponent {

  users = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }];
  checked: boolean = true
  constructor() { }
  selected: any = [];

  canbeChecked(id): boolean {
    console.log(this.selected.includes(id));
    return this.selected.includes(id);
  }

  userSelectClick(id) {

    if (!this.selected.includes(id)) {
      if (id == 2){
         this.selected.push(id);
      }
      else{
         return false;
      }
    }
    else {
      if(id == 2){
        this.selected = [];
      }
      else
       return false;
    }
  }

}

Here is a working link

https://stackblitz.com/edit/mat-checkbox-conditional-z8uc94

Share:
12,702
devN
Author by

devN

JS &lt;3

Updated on June 09, 2022

Comments

  • devN
    devN almost 2 years

    I have a user table list with mat-checkbox. When mat-checkbox is clicked, the checkbox should be checked only if a certain condition is true.

    Here in this code, I am trying to have checkbox checked only for id=2. But as you can see, initially when checkbox of 2 is clicked, it doesn't get checked even though 2 is added to array of elements which should be checked.

    On the other hand, when checkbox of 1,3 or 4 is clicked, they get checked.

    component.html

    <tbody>
        <tr *ngFor="let user of users; let in = index">
                <td>
                    <mat-checkbox [ngModel]="canbeChecked(user.id)" (click)="userSelectClick(user.id)"></mat-checkbox>
                </td>
        </tr>
    </tbody>
    

    component.ts

    export class AppComponent {
    
      users = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }];
      checked: boolean = true
      constructor() { }
      selected: any = [];
    
      canbeChecked(id): boolean {
        console.log("check " + id)
        console.log(this.selected)
        return this.selected.includes(id);
    
      }
    
      userSelectClick(id) {
    
        if (!this.selected.includes(id)) {
          if (id == 2)
            this.selected.push(id);
          console.log("select " + id)
          console.log(this.selected)
        }
        else {
          this.selected = this.selected.filter(item => item !== id)
        }
    
      }
    
    }
    

    Working code: https://stackblitz.com/edit/mat-checkbox-conditional