Angular 2, checkbox two-way model binding, dom, not reflecting the checked status when manipulating state from a component

Per plunker

I have a number 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>

When checking all three flags, all of them must be canceled:

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, I see that this works the first time around, but subsequently, when checking the third flag, the model is updated to false, however, the flag remains set in the user interface, becoming out of sync.

Now I fixed it by passing the event and switching the checked state of the target dom element. But I wonder how this can become incompatible in the first place? Is there a better solution?

+4
source share
1 answer

false, , true, false, Angular " t ( true, ).

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}`)
}

+2

Source: https://habr.com/ru/post/1671568/


All Articles