angularngforngmodel

Set ngModel sub-property dynamically


I need to set a ngModel sub-property dynamically like this inside an ngFor.

<div *ngFor="let weekday of this.weekdays">
  <mat-slide-toggle [(ngModel)]="openingHoursObj.[weekday].isOpen">Open</mat-slide-toggle>
</div>

... where weekday can be monday, tuesday, wednesday etc.

It says: Property weekday does not exist on OpeningHoursViewModel.

How can you go about setting this sub-property dynamically in similar fashion?


Solution

  • Try removing this. from this.weekdays and removing the first . from openingHoursObj.[weekday].isOpen. That will access the class property and object properties correctly, respectively.

    Result:

    <div *ngFor="let weekday of weekdays">
      <mat-slide-toggle [(ngModel)]="openingHoursObj[weekday].isOpen">Open</mat-slide-toggle>
    </div>