I have a class Offer which have one property "units" as array of objects.
export class Offer {
public propertyA: string;
public propertyB: string;
public units: Unit[];
}
export class Unit {
public code: string,
public name: string,
public checked: boolean
}
I am using Angular2, these units must be checkboxes the user can select. Also I am using angular material.
The html code looks like:
<div *ngFor="let unit of model.units; let i=index">
<mat-checkbox [(ngModel)]="model.units[i].checked"
id="units[{{i}}]" name="units[{{i}}]">
{{ unit.name }}
</mat-checkbox>
</div>
The units property is loaded using:
this.model.units.push(new Unit("code1","name1", false));
this.model.units.push(new Unit("code2","name2", false));
this.model.units.push(new Unit("code3","name3", false));
When I send the form the checked property does not contains the checked value.
What am I doing wrong??
In order to work you gotta give an unique
name
to your ngModel binded input.Example taking your code:
I prefer not to use the array notation in these cases (
units[{{i}}]
), because it means that all fields are joined in the same thing, but as your code seems to work this is just a preference and not the cause of the error.Add
[checked]="unit.checked"
and removengModel
,id
andname
from yourmat-checkbox
. This does one way binding when you load the page but to make the two way binding work you need to do something similar like this which i have done in my project:Pass the
$event
on change and set the value in the component file manually:Change your HTML to:
Add this to Component file:
EDIT/UPDATE: Found a solution recently for two way binding without handling it explicitly
Make sure
model.units
have a property forchecked
. This is the easiest way to add it:component.ts:
html:
If you want to control the enable/disable options as well try adding this:
component.ts:
html:
This work for me tested in Angular 7.
Just to make sure that name is unique for each checkbox