javascript - Filtro Pipe de Angular para KeyValue y Autocompletar
Primero que nada quiero mostrar los países con esta tubería y filtrarlos con los caracteres insertados y necesito los códigos ISO para mostrar las banderas de los países. El problema es que quiero usar una biblioteca que tenga todos los países con códigos ISO y demás. Esto tiene la forma de clave-valor.
Primero, exporto estos datos a una variable para poder usar los datos.
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);
}
}
En el HTML puedo usar esto así:
<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>
La forma normal que también puedo usar pero completamente sin la manera de clave-valor y justo como dicen los ejemplos de Angular (sin la lógica de 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>
Eso solo me da el nombre completo del país, como Argelia o algo así.
He encontrado una idea aquí https://long2know.com/2017/04/angular-pipes-filtering-on-multiple-keys/ pero no pude adaptarla a mis propósitos. Sería aún más perfecto si pudiera filtrar por clave y valor, así tal vez "DE" para la clave y "Ger" para el valor de Alemania. No parece ser posible con los pipes existentes.
Editar bajo solicitud (filtrando):
private _filter(value: string): string[] {
var filterValue;
if (value) {
filterValue = value.toLowerCase();
} else {
filterValue = "";
}
return this.countries.filter(option => option.toLowerCase().startsWith(filterValue));
}
También se actualizó el ngOnInit()
Respuesta #1
Lo hice funcionar con la biblioteca i18n e incluso con flag-icon-css
TypeScript (clase de filtro):
@Pipe({
name: 'filterLanguages'
})
export class FilterLanguages implements PipeTransform {
transform(items: any, filter: any, isAnd: boolean): any {
if (filter && Array.isArray(items)) {
let filterKeys = Object.keys(filter);
if (isAnd) {
return items.filter(item =>
filterKeys.reduce((memo, keyName) =>
(memo && new RegExp(filter[keyName], 'gi').test(item[keyName])) || filter[keyName] === "", true));
} else {
return items.filter(item => {
return filterKeys.some((keyName) => {
return new RegExp(filter[keyName], 'gi').test(item[keyName]) || filter[keyName] === "";
});
});
}
} else {
return items;
}
}
}
HTML :
<mat-form-field class="field-sizing">
<input matInput required placeholder="{{ 'REGISTRATION.COUNTRY' | translate }}" name="country"
id="country" [matAutocomplete]="auto" formControlName="country" [value]="filterText" />
<mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
<mat-option *ngFor="let item of countries | filterLanguages:{ name: filterText, iso: filterText, flagId: filterText } : false" [value]="item.name">
<span class="flag-icon flag-icon-{{item.flagId}} flag-icon-squared"></span>
{{ item.name }} - {{ item.iso }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
TypeScript (componente):
export var countryList: {
[key: string]: string
}
declare const require;
export class YourComponent implements OnInit {
countries = [] as Array<any>
currentLanguage: string;
filterText: string;
ngOnInit() {
i18nIsoCountries.registerLocale(require("i18n-iso-countries/langs/en.json"));
i18nIsoCountries.registerLocale(require("i18n-iso-countries/langs/de.json"));
this.currentLanguage = this.translateService.currentLang;
countryList = i18nIsoCountries.getNames(this.currentLanguage);
this.buildForm();
this.createCountries();
this.personalForm.controls['country']
.valueChanges
.pipe(debounceTime(100))
.pipe(distinctUntilChanged())
.subscribe(term => {
this.filterText = term;
});
}
ngAfterContentChecked() {
this.cdRef.detectChanges();
if (this.currentLanguage != this.translateService.currentLang) {
countryList = i18nIsoCountries.getNames(this.translateService.currentLang);
this.createCountries();
this.currentLanguage = this.translateService.currentLang;
this.personalForm.get('country').updateValueAndValidity();
}
}
createCountries() {
this.countries = [];
for (let key in countryList) {
var countryName: string = countryList[key];
var isoValue: string = key;
var isoLowerValue: string = key.toLowerCase();
this.countries.push({ name: countryName, iso: isoValue, flagId: isoLowerValue })
}
}
Necesitas la biblioteca i18n y, como en mi ejemplo, un formControl.
