Reputation: 845
Initially i want to push all the menus into an array with a status of 0 using an initial event trigger,and then make it 1 if it is checked otherwise 0 itself.Is it possible to do an event change when the ngFor loading initially?
**app.html**
<div *ngFor="let menu of menus" class="checkbox">
<label>
<input type="checkbox" (change)="updateChecked(menu,$event)">
{{menu.name}}
</label>
</div>
Upvotes: 1
Views: 443
Reputation: 3186
attach your menu.status
to [(ngModel)]
then angular does the job for you, all you need to is provide an array with initial status value for checkbox whether it is 1 or 0
, ngModel
will change the status value according to checkbox value, internally javascript treats 1 and 0
as true or false
when you toggle the checkbox, so menu.status
will be true or false
in output, below is the working snippet
<ul>
<li *ngFor="let menu of menus; let i = index">
<label>
<input type="checkbox" [(ngModel)]="menu.status" (change)="updateChecked(menu, $event)" class="" />{{menu.name}}
</label>
</li>
</ul>
in your typescript file
export class AppComponent{
menus: any[];
constructor() {
this.menus = [
{
name: 'home',
status: 0
},
{
name: 'about',
status: 1
}
]
}
updateChecked(menu, event) {
console.log(this.menus); // inspect menu, menus and event here
}
}
Upvotes: 1