Reputation: 161
I am using Angular 2 + Typescript, and I've just started for a short time. I want to make a list of checkboxes and check their states.
Like in some shopping websites, checkboxes are the companies, select some and press the search button to show the products of the selected companies.
<ul class="companies">
<li *ngFor="let company of companies">
<input type="checkbox">{{ companies.name }}
</li>
</ul>
"companies" is an array taken from database. Each company simply has an id and a name. *ngFor will repeat the li for each element in the array. Each li contains a checkbox and a plain text.
I can't give each checkbox an id. Thus, I don't know how to check their states. I appreciate for any help.
Upvotes: 0
Views: 1358
Reputation: 3994
If you used a mat-checkbox
you could use the @Output() change: EventEmitter<MatCheckboxChange>
event call a method when the value state changes. This would look something like this:
<ul class="companies">
<li *ngFor="let company of companies">
<mat-checkbox (change)="onCheckboxStateChange($event, company.id);">{{ companies.name }}</mat-checkbox>
</li>
</ul>
Then you would need a onCheckboxStateChange(changeEvent: MatCheckboxChange, id: number)
method in your ts class to handle the check event. The changeEvent
has a property checked
which you can use as follows:
public onCheckboxStateChange(changeEvent: MatCheckboxChange, id: number) {
const index = this.companies.findIndex(x => x.id === id);
if (index === -1) {
console.warn("Company not found");
return;
}
companies[index].checked = changeEvent.checked;
}
Upvotes: 1