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;
});
}
CodePudding user response:
Here is my solution:
onChangeContinentCheckBox(event: MatSelectChange) {
this.filteredCountries = this.countries.filter((country: ICountry) => {
if (event.value.length >= 1) {
return this.selectedContinents.value?.includes(country.continent);
}
return this.countries;
});
}
CodePudding user response:
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 ];
}