Reputation: 8730
In component I have define checkboxes
public groceries = [
{ name: 'Seitan', bought: false },
{ name: 'Almond Meal Flour', bought: false },
{ name: 'Organic Eggs', bought: false }
];
In model I make groceries as string
export class User {
id: number,
email: string,
password: string,
firstName: string,
lastName: string,
groceries: string,
}
component.html
<span *ngFor="let grocery of groceries">
<label>
<input type="checkbox" name="groceries" [(ngModel)]="user.groceries"
[value]="grocery.name">
{{grocery.name}}
</label>
</span>
Issue is that by this when I select one checkbox all others are selected. I am confuse and not on track to implement this checkbox feature.
Upvotes: 0
Views: 1965
Reputation: 657118
You bind a number of checkboxes to the same user.groceries
.
Either bind them to a property of grocery
(the iteration variable of *ngFor
, or create another array where you bind each checkbox to a different array entry.
<span *ngFor="let grocery of groceries">
<label>
<input type="checkbox" name="groceries" [(ngModel)]="grocery.isChecked"
{{grocery.name}}
</label>
</span>
or
checkedGroceries = new Array(groceries.length);
<span *ngFor="let grocery of groceries; let i=index">
<label>
<input type="checkbox" name="groceries" [(ngModel)]="checkedGroceries[i]"
{{grocery.name}}
</label>
</span>
You don't need [value]
. The value is assinged already by [(ngModel)]="..."
Upvotes: 3