【发布时间】:2021-03-07 11:29:25
【问题描述】:
我正在尝试根据用户输入以名称与值不同的形式过滤对象数组。如何使代码(适用于字符串数组)与对象数组一起使用?
HTML
<input type="text" placeholder="{{ 'string' | translate }}*" matInput formControlName="example" [matAutocomplete]="exampleAutoComplete" (keyup)="filterExample($event)">
<mat-autocomplete #exampleAutoComplete="matAutocomplete" [displayWith]="displayExample">
<mat-option *ngFor="let example of exampleArray" [value]="example.id">
{{example.name | titlecase }}
</mat-option>
</mat-autocomplete>
<mat-error *ngIf="companyInfoFormGroup.get('example').invalid">
<ng-container *ngIf="companyInfoFormGroup.get('example').errors.required">
string
</ng-container>
<ng-container *ngIf="companyInfoFormGroup.get('example').errors.example">
string
</ng-container>
<ng-container *ngIf="companyInfoFormGroup.get('example').errors.maxlength">
string
</ng-container>
</mat-error>
</mat-form-field>
类型脚本
displayExample = (id: string): string => {
if (!id) {
return '';
}
this.exampleName = this.exampleArray.find((item: { id: string, name: string }) => {
return item.id === id;
}).name;
return this.exampleName;
}
public filteredExamples(event): void {
this.filteredExampleNames = this.filteredExampleNames
.filter((example: string) => example.toLowerCase().includes(event.target.value.toLowerCase()));
}
我意识到这是过滤字符串 [] 的方法。但是我不知道如何让它适用于对象数组。
对象
{
"id": "f0493847-f05e-ea11-a811-342cd25c7c6",
"name": "example 1"
}
【问题讨论】:
标签: angular typescript angular-material angular-forms