【发布时间】:2022-10-17 22:32:42
【问题描述】:
我正在尝试根据检查的大陆过滤国家列表。
我相信事情的模板方面是在一个好地方:
ngOnInit() {
this.filteredCountries = this.countries;
this.selectedContinents.valueChanges.subscribe(selectedValue => {
this.filteredCountries = this.countries.filter(country => {
return this.selectedContinents.value?.includes(country.continent);
});
}
}
<mat-form-field class="country-code-dialog-search-container">
<input matInput (change)="onChangeContinentCheckBox()" placeholder="Filter by Continents" cdkFocusInitial>
<mat-select placeholder="Filter by Continents" multiple>
<mat-option *ngFor="let continent of getContinents()">{{continent}}</mat-option>
</mat-select>
</mat-form-field>
<section class="example-section" *ngFor="let country of filteredCountries">
<span class="example-list-section">
<mat-checkbox class="example-margin">
{{country.name}} ({{country.iso3}}) <span>{{country.emoji}}</span>
</mat-checkbox>
</span>
</section>
我见过这样的事情:
<mat-options type="checkbox" *ngFor="let continent of getContinents() | selectedContinents">{{continent}}</mat-options>
在函数中:
onChangeContinentCheckBox() {
this.countries.filter('selectedCountries', function(country) {
return country.continent === /* logic for obtaining checked selection */
});
}
但这只是破坏了我的应用程序,这意味着 mat-form-field 不再呈现,国家名称、ISO 和表情符号也不再呈现,所以它只是一个空的复选框呈现列表。
所以这是我在 Stackblitz 上的一个例子:
【问题讨论】:
-
请更具体。 “破坏您的应用程序”是什么意思?
-
@E.Maggini,我为打破应用程序的含义添加了一些清晰度。
-
您需要将您的
mat-select绑定到一个变量并在您的过滤器中使用它,使用您拥有的代码我看不到您使用的是反应式表单还是模板驱动的表单,对于反应式表单,您需要使用[formControl]='selectedCountries']和用于模板驱动使用[(ngModel)]="selectedCountrie" -
@Juan,所以你指的是
[(value)]="selectedContinent" -
在 stackblitz 或其他上创建问题的最小再现对于更快/更准确地获得答案很有用。 stackoverflow.com/help/how-to-ask
标签: javascript angular