Issue
So I have a selectionChange that filters a list upon selecting a checkbox, but when the user unselects the checkbox, the list does not return to its unfiltered state, it returns an empty array and I am not sure how to fix that the Angular way.
I have a method on that checkbox list called onChangeContinentCheckBox()
onChangeContinentCheckBox() {
this.filteredCountries = this.countries.filter((country: ICountry) => {
return this.selectedContinents.value?.includes(country.continent);
});
}
Which is applied in the template with a selectionChange, but there is another method that matches between the key of the continents json file to the value of the property of countries json file.
getContinents() {
Object.keys(this.continents as IContinents).forEach((key) => {
this.continentsObj.push({
name: this.continents[key],
code: key
});
});
}
And that getContinents() gets passed into ngOnInit() and this is how its being applied in the template file.
<mat-form-field>
<mat-select [formControl]="selectedContinents" placeholder="Filter by Continents" multiple (selectionChange)="onChangeContinentCheckBox()">
<mat-option *ngFor="let continent of continentsObj" [value]="continent.code">{{continent.name}}</mat-option>
</mat-select>
</mat-form-field>
I am thinking something like:
onChangeContinentCheckBox() {
this.filteredCountries = this.countries.filter((country: ICountry) => {
if (checkbox.checked) {
return this.selectedContinents.value?.includes(country.continent);
}
return this.countries;
});
}
Solution
Why are you returning this.countries inside the filter method?
Your solution works because this.countries exists and resolves as truthy. You could as well replace it with return true.
Or you could try something like this instead:
onChangeContinentCheckBox() {
this.filteredCountries = (this.selectedContinents.value?.length > 0) ?
this.countries.filter((country: ICountry) =>
this.selectedContinents.value?.includes(country.continent)) :
[ ...this.countries ];
}
Answered By - Vasileios Kagklis
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.