【发布时间】:2019-06-11 01:41:20
【问题描述】:
首先我想用这个管道显示国家并用插入的字符过滤它们,我需要 ISO 代码来显示国家的标志。问题是我想使用一个图书馆,它拥有所有国家的 ISO 代码和东西。这有键值形式。
首先我将这些数据导出到 var 以便能够使用这些数据。
export var indexedArray: { [key: string]: string }
countryStuff: Country; //currently not used
countries = [] as Array<string>
filteredCountries: Observable<string[]>;
export interface Country { //currently not used
[key: string]: string
}
ngOnInit() {
this.startDate.setFullYear(this.startDate.getFullYear() - 18);
this.buildForm();
this.filteredCountries = this.personalForm.controls['country'].valueChanges
.pipe(
startWith(''),
map(value => this._filter(value))
);
i18nIsoCountries.registerLocale(require("i18n-iso-countries/langs/en.json"));
i18nIsoCountries.registerLocale(require("i18n-iso-countries/langs/de.json"));
this.currentLanguage = this.translateService.currentLang;
indexedArray = i18nIsoCountries.getNames(this.currentLanguage);
for (let key in indexedArray) {
let value = indexedArray[key];
this.countries.push(value);
}
}
在 html 中我可以这样使用:
<mat-option *ngFor="let item of countryStuff | keyvalue:keepOriginalOrder" [value]="item.key">
Key: <b>{{item.key}}</b> and Value: <b>{{item.value}}</b>
</mat-option>
我也可以使用正常方式,但完全没有键值方式,就像 Angular 示例所说(没有 TS 逻辑):
<mat-option *ngFor="let option of filteredCountries | async" [value]="option">
<span class="flag-icon flag-icon-de flag-icon-squared"></span>
{{option}}
</mat-option>
这只是给了我完整的国家名称,例如阿尔及利亚之类的。
我在这里找到了一个想法https://long2know.com/2017/04/angular-pipes-filtering-on-multiple-keys/,但我无法为我的目的更改它。如果我可以过滤 key 和 value,那将更加完美,所以也许“DE”用于键,“Ger”用于德国的值。现有管道似乎无法实现。
按需编辑(过滤):
private _filter(value: string): string[] {
var filterValue;
if (value) {
filterValue = value.toLowerCase();
} else {
filterValue = "";
}
return this.countries.filter(option => option.toLowerCase().startsWith(filterValue));
}
还更新了ngOnInit()
【问题讨论】:
-
DE和Ger分别代表key和value?
-
是的,抱歉。我编辑那个。 @wentjun
-
没人知道吗?我不擅长管道..
-
抱歉,我可以知道过滤的方式和位置吗?
-
@wentjun 完成。如果你还需要什么告诉我
标签: javascript angular typescript angular-pipe