Home > Back-end >  How can I use ngIf to set the ngModel in a loop
How can I use ngIf to set the ngModel in a loop

Time:02-25

How can I use ngIf to set the ngModel within a ngFor loop?

I am using Angular 8.2.14 with @progress/kendo-angular-inputs

Within the code below, how do I use ngif to set the ngModel to true if option === checked?
Otherwise all of the checkboxes are checked, not just the one that should be checked.

<div*ngFor="let option of contacts">
  <input
    style="width: auto; margin-right: 10px"
    type="checkbox"
    value="{{ option }}"
    [(ngModel)]="checked"
    kendoCheckBox
  />
  <label for="{{ option }}">{{ option }}</label>
</div>

CodePudding user response:

Why do you even an ngIf in the first place ( with the ngIf you'll hide your checkbox anyway ). I think what do you want to achieve it's something like this.

// in your html
<div *ngFor="let option of contacts">
<input
  style="width: auto; margin-right: 10px"
  type="checkbox"
  [checked]="checked === option"
  (change)="changeCheck(option)"
 />
 <label for="{{ option }}">{{ option }}</label>
</div>

// in your ts
  contacts = ['a', 'b', 'c'];
  checked = 'a';

In this way you're gonna create 3 checkboxes and you can check each one individually.

  • Related