I want to display an array of objects which have a group
property in a list, and be able to display only those of a certain group depending on what the user wants.
In order to do that, I have checkboxes to collect the user's wish:
<div class="input-controls">
<label>Select the group(s) you want to display:</label>
<div *ngFor="#group of groups">
<label>
<input type="checkbox"
name="groups"
value="group"
[checked]="true"
(change)="updateSelectedGroups(group, $event)"/>
{{group}}
</label>
</div>
</div>
And then, I would like to be able to only display the objects with their group
property selected. I first tried to only display the selected groups:
Selected Group(s):
<ul>
<li *ngFor="#group of selectedGroups">
{{group}}
</li>
</ul>
I have managed to create a selectedGroups
object, which contains an array of only the selected groups:
export class ListComponent {
private groupsMap = {
'Group A': true,
'Group B': true,
'Group C': true
};
private groups = ['Group A', 'Group B', 'Group C'];
private selectedGroups: string[];
constructor() {
this.selectedGroups = ['Group A', 'Group B', 'Group C'];
}
updateSelectedGroups(group, event) {
// groupsMap object is updated
this.groupsMap[group] = event.target.checked;
// selected groups are pushed into selectedGroups
this.selectedGroups = [];
for(var x in this.groupsMap) {
if(this.groupsMap[x]) {
this.selectedGroups.push(x);
}
}
console.log(this.selectedGroups);
}
}
As shown, I have put a console.log(this.selectedGroups)
to verify that my selectedGroups
object really only contains the selected groups I want, and update properly when checking/unchecking a checkbox. And it does.
The problem is, when I check/uncheck or checkbox, the list of the selected groups doesn't update in my view. It get stuck as if selectedGroups
was still equal to ['Group A', 'Group B', 'Group C']
all the time.
Does anyone know why? Does it have something to do with the behaviour of *ngFor
? If so, what can I do to have the behaviour I want?
I have tried an other method using *ngIf
and groupsMap
, but it doesn't work neither:
<ul>
<li *ngFor="#group of groups">
<span *ngIf="groupsMap[group]">{{group}}</span>
</li>
</ul>
I would be happy to find a solution, one way or another. Any help would be really appreciated, thank you!
Aucun commentaire:
Enregistrer un commentaire