4

Per Plunker

I have a series of checkboxes:

<label><input type="checkbox" name="foo" [(ngModel)]="foo" (change)="changed()">Foo</label>
<label><input type="checkbox" name="bar" [(ngModel)]="bar" (change)="changed()">Bar</label>
<label><input type="checkbox" name="baz" [(ngModel)]="baz" (change)="changed()">Baz</label>

On checking all three checkboxes, they should all revert to unchecked:

changed() {
  if (this.foo && this.bar && this.baz) {
    this.foo = false;
    this.bar = false;
    this.baz = false;
  }

  console.log(`foo: ${this.foo};bar: ${this.bar};baz: ${this.baz}`)
}

Instead what I see is that first time around it seems to work, but subsequently, on checking the third checkbox, the model updates to false, however the checkbox remains checked in the UI, becoming out of sync.

For now I have fixed it by passing in the event and toggling the checked state of the target dom element myself. But I wonder how it can become out of sync in the first place? Is there a better solution?

1 Answer 1

2

If the value is false and you click the checkbox to change the value to true and the event handler changes it back to false, then Angular change detection doesn't see a change and doesn't update bindings (the checkbox keeps its true value though).

constructor(private cdRef:ChangeDetectorRef) {}

changed() {
  this.cdRef.detectChanges();
  if (this.foo && this.bar && this.baz) {
    this.foo = false;
    this.bar = false;
    this.baz = false;
  }
  console.log(`foo: ${this.foo};bar: ${this.bar};baz: ${this.baz}`)
}

Plunker example

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.