Объект автозаполнения Angular, где имя объекта отличается от значения

Я пытаюсь отфильтровать массив объектов на основе пользовательского ввода в форме, где имя отличается от значения. Как включить код (работающий для массива строк) для работы с массивом объектов?

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"
}

person Maartenw    schedule 24.11.2020    source источник


Ответы (1)


Утомительным способом вы можете проверить атрибуты, содержащие строку:

public filteredExamples(event): void {
    const filteredValue = event.target.value.trim().toLowerCase();
    this.filteredExampleNames = this.filteredExampleNames
        .filter((example: object) => {
            return example.id.toLowerCase().indexOf(filteredValue) !== -1 ||
                example.name.toLowerCase().indexOf(filteredValue) !== -1
        });
}```
person Quentin Fonck    schedule 24.11.2020