mardi 2 octobre 2018

One-way binding a checkbox with [ngModel] does not work in Angular 6

We are developing an app with Angular 6 and NgRX (Redux-Pattern). I have a checkbox in my template discovery.component.html:

<label>
  <input type="checkbox" name="wrongSpelling"
    [ngModel]="state.wrongSpelling" (click)="toggleWrongSpelling($event)" />
  Wrong Spelling
</label>

According to Redux-pattern, the dataflow should look like this:

  1. User clicks on the checkbox. The checkbox is not toggled but an update action is dispatched. Also the state is not updated (One-way binding)

  2. render() is called with the new state and with the updated entity. The updated entity is assigned to the component.

  3. The checkbox's state should update depending on the updated entity.

The relevant code of discovery.component.ts is given below:

public state;

render(state) {
  if (state.discovery) {
    this.state = state.discovery;
  }
}    

toggleWrongSpelling(event) {
  event.preventDefault();
  this.discoveryAction.update({
    wrongSpelling: !this.state.wrongSpelling // it's safe that state exists here
  });
}

However, the checkbox does not get checked on click.

Things I'v tried (without success):

  • Debugging render(): this.state.wrongSpelling is indeed toggled every time I click on the checkbox
  • create a member in my DiscoveryComponent wrongSpelling which is toggled in toggleWrongSpelling() and read in the template (instead of the state) (I thought about changeDetection strategies that might be the problem here)
  • used [value], [checked] and (for testing) [(ngModel)] instead of [ngModel] in the template
  • replaced Wrong Spelling with to see if there is a timing problem
  • used the safe-navigation-operator: [ngModel]="state?.wrongSpelling"

so the problem seems to be in the template. What could be wrong here?




Aucun commentaire:

Enregistrer un commentaire