Angular 2: Default checked on checkbox in ngFor

Martin Brandhaug picture Martin Brandhaug · Jul 13, 2017 · Viewed 42.6k times · Source

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.

Answer

Martin Brandhaug picture Martin Brandhaug · Jul 13, 2017

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;
    }
  }