【问题标题】:Angular Autocomplete Object where Object name is different then value角度自动完成对象,其中对象名称与值不同
【发布时间】: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


    【解决方案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
            });
    }```
    

    【讨论】:

      猜你喜欢
      • 2018-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多