【发布时间】:2023-01-06 22:38:42
【问题描述】:
https://stackblitz.com/edit/angular-ivy-s2ujmr?file=src/app/pages/home/home.component.html
我正在尝试使下拉菜单用于过滤您在其下方看到的标志。
我想我可以实现类似于我为搜索栏过滤方法所做的事情,比如:
主页.component.ts
export class HomeComponent implements OnInit, OnDestroy {
constructor(private api: ApiService){}
regionOptions = ['Africa', 'Americas', 'Asia', 'Europe', 'Oceania'];
countries!: Country[];
displayCountries?: Country[];
destroy$ = new Subject<void>()
countryControl = new FormControl();
ngOnInit(){
this.api.getAllCountries().subscribe((response: Country[]) => {
this.countries = response;
this.displayCountries = response;
});
this.countryControl.valueChanges.pipe(takeUntil(this.destroy$),debounceTime(100)).subscribe((value: string) => this.updateDisplayCountries(value))
}
//SEARCH BAR
private updateDisplayCountries(searchTerm: string): void {
this.displayCountries = this.countries.filter((country: Country ) => this.isCountrySearched(country, searchTerm.toLowerCase()))
}
private isCountrySearched(country: any, searchTerm: string): boolean {
return country.name.common.toLowerCase().includes(searchTerm) || country.name.official.toLowerCase().includes(searchTerm)
}
//DROPDOWN <-------------------------------------------THIS PART
private updateDisplayRegions(region: string): void {
this.displayCountries = this.countries.filter((country: Country ) => this.isRegionFiltered(country, region.toLowerCase()))
}
private isRegionFiltered(country: any, selectedRegion: string): boolean {
return country.region.toLowerCase().includes(selectedRegion)
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
}
然后在 HTML 中添加一个“(change)”事件监听器,如下所示:
主页.component.html
<div class="drop-down">
<select (change)="updateDisplayRegions($event.target.value)">
<option *ngFor="let region of regionOptions" value="{{region}}">{{region}}</option>
</select>
</div>
但是为了使它起作用(如果它甚至是您这样做的方式或者它是否真的起作用,哪个 idk)我需要将下拉选择值传递给函数。我习惯在其他框架中使用“event.target.value”,但在 Angular 中我遇到了错误:
对象可能为“null”.ngtsc(2531)
类型“EventTarget”上不存在属性“值”.ngtsc(2339)
如何将下拉选择的值传递给更改函数,以便它可以继续进行过滤? angular 使用什么代替“event.target.value”?
我是不是完全错了?
【问题讨论】:
-
updateDisplayRegions方法应该是公开的,因为你正在将它绑定到模板,否则它会编译失败。
标签: javascript angular typescript rxjs observable