Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: Default checked on checkbox in ngFor

I'm trying to set default value as checked on a checkbox inside my ngFor. This is my array of checkbox items:

tags = [{
  name: 'Empathetic',
  checked: false
}, {
  name: 'Smart money',
  checked: true
}, {
  name: 'Minimal help after writing check',
  checked: false
}, {
  name: 'Easy term sheet',
  checked: true
}];

This is my html

<div class="form-group">
  <div class="form-check" *ngFor="let tag of tags;">
    <label class="form-check-label" for="tag{{tag.value}}">
      <input
        class="form-check-input"
        type="checkbox"
        id="tag{{tag.value}}"
        name="tagOptions"
        [(ngModel)]="tag.checked">
      {{tag.name}}
    </label>
  </div>
</div>

The desired result is to get 2 checked, and 2 unchecked boxes, but all of them are unchecked. I've also tried different variations with [checked]="tag.checked", but it didn't seem to do the trick.

like image 745
Martin Brandhaug Avatar asked Jul 13 '17 19:07

Martin Brandhaug


2 Answers

This solved my problem with the checked/unchecked checkboxes, while I still had control over changes in my variables.

HTML

<div class="form-group">
  <div class="form-check" *ngFor="let tag of tags; let i = index;">
    <label class="form-check-label" for="tag{{tag.value}}">
      <input
        class="form-check-input"
        type="checkbox"
        id="tag{{tag.value}}"
        name="tagOptions"
        (change)="changeCheckbox(i)"
        [checked]="tag.checked">
      {{tag.name}}
    </label>
  </div>

.ts

  changeCheckbox(tags, i) {
    if (tags) {
      this.tags[i].checked = !this.tags[i].checked;
    }
  }
like image 179
Martin Brandhaug Avatar answered Nov 06 '22 04:11

Martin Brandhaug


Use the checked property instead of ngModel,

 <div class="form-group">
      <div class="form-check" *ngFor="let tag of tags">
        <label class="form-check-label" for="tag{{tag.value}}">
          <input
            class="form-check-input"
            type="checkbox"
            id="tag{{tag.value}}"
            name="tagOptions"
            [checked]="tag.checked">
          {{tag.name}}
        </label>
      </div>
   </div>

DEMO

like image 6
Sajeetharan Avatar answered Nov 06 '22 03:11

Sajeetharan