V. Benavides V. Benavides - 5 months ago 38
TypeScript Question

Binding array of ids to dynamically generated checkboxes in Angular4

Good evening developers, so I have this issue when binding my checkboxes generated dynamically to values in an array. Basically I have the following in my users.template.html file:

<div *ngFor="let r of roles" class="checkbox">
<label for="">
<input type="checkbox" id="{{ r.name }}" (change)="onRoleChange(r.name, $event)" [checked]="userRoles.includes(r.name)"> {{ r.name }}

Basically what it does is updates the roles a user has based on the given checkboxes that are generated dynamically. Now the (change) works wonderfully but the [checked] is throwing an error saying the following:

Cannot read property 'includes' of undefined

I have no idea why because everywhere I looked it points me to use that kind of binding for this type of dynamic content. So any pointers would be awesome if you have them please. Thank you all in advance for any advice.

Answer Source

you cannot call inherited methods of an object of a particular type directly in a template as per my understanding. You can call a component method instead which does that calculation for you.

<input type="checkbox" id="{{ r.name }}" (change)="onRoleChange(r.name, $event)" [checked]="presentInUserRoles(r.name)">


presentInUserRoles(role: string): boolean {
 return this.userRoles.includes(role);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download