【问题标题】:Angular Material Automcomplete filteringAngular 材质自动完成过滤
【发布时间】:2021-06-10 21:45:58
【问题描述】:

我有一个 json 对象,如下所示:

[
   {
      "personId":"ac9be7ef-ab23-4ed9-a77e-7e844f5ef902",
      "fullName":"X1, X1."
   },
   {
      "personId":"5a88203a-e69e-4103-bc05-b99c83f1a6cd",
      "fullName":"X2, X2"
   },
   {
      "personId":"17a39787-2122-4149-b767-d8075cd42c1a",
      "fullName":"X3, X3"
   }
]

我想使用自动完成组件来过滤掉人。

我已经这样定义了我的 formControl:

fromControl = new FormControl("", [Validators.required]);

在 html 中我是这样的

<mat-form-field appearance="outline" class="form-field">
   <mat-label>From</mat-label>
   <input type="text"
   placeholder="Type in the person name"
   aria-label="Text"
   [errorStateMatcher]="matcher"
   matInput
   [formControl] = "fromControl"
   [matAutocomplete]="auto">
   <mat-icon matSuffix>person</mat-icon>
   <mat-error *ngIf="fromControl?.hasError('required')">
      From client selection is required!
   </mat-error>
   <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
      <mat-option *ngFor="let c of from" [value]="c.personId">
      {{ c.fullName }}
      </mat-option>
   </mat-autocomplete>
</mat-form-field>

现在单击控件或过滤选项时,它将填充所有名称/过滤名称,但是,选择名称时,它将将personid放在控件中作为选定的值。

显示的值仍应为全名

这是我的 stackBlitz example

【问题讨论】:

  • 你想在输入中显示名字吗?试试这个 {{ option.fullName }} 将在输入中显示名称。
  • stackblitz 示例正在正确过滤,但在选择名称时,它显示的是 personId 而不是所选名称.. 这种奇怪的行为

标签: angular angular-material


【解决方案1】:
<mat-form-field appearance="outline" class="form-field">
   <mat-label>From</mat-label>
   <input type="text"
   placeholder="Type in the person name"
   aria-label="Text"
   [errorStateMatcher]="matcher"
   matInput
   [formControl] = "fromControl"
   [matAutocomplete]="auto">
   <mat-icon matSuffix>person</mat-icon>
   <mat-error *ngIf="fromControl?.hasError('required')">
      From client selection is required!
   </mat-error>
   <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
      <mat-option *ngFor="let c of from" [value]="option.fullName">
      {{ option.fullName }} 
      </mat-option>
   </mat-autocomplete>
</mat-form-field>

【讨论】:

  • 嗨,滨田。如果您看到我的 stackblitz 示例,我正在使用 option.fullName.. 但是当您选择该选项时,它会将 personId 而不是所选名称放在自动完成框中
  • 在值和输入 option.fullName?并在 Method 中获取 id。
  • 我想过这个,但整个自动完成行为对我来说很奇怪。如果这是通过 selectionChange 事件完成的,那么它就是这样。谢谢滨田
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-09
  • 2020-07-31
  • 2016-03-23
  • 1970-01-01
  • 2018-05-26
  • 1970-01-01
  • 2019-02-06
相关资源
最近更新 更多