【问题标题】:How to set value taken from a database as default value for Angular Material Autocomplete如何将从数据库中获取的值设置为 Angular Material Autocomplete 的默认值
【发布时间】:2018-11-08 07:53:36
【问题描述】:

我想从数据库中获取一个值并将其设置为自动完成输入框中的默认值。

填充客户端类型

clientTypes: any[] = [];
getClientTypes() {
    this.clientService.getClientTypes()
    .subscribe((data: any) => {
        this.clientTypes = [...data];
    });
}

用于自动完成 DisplayWith

displayFn(object): string {
    console.log(object.ClientTypeId);
    return object.Name;
}

在 html 中

<mat-form-field appearance="outline">
    <mat-label>Client Type</mat-label>
    <input type="text" placeholder="Select Client Type" aria-label="Number" matInput formControlName="clienttype"  [formControl]="clientTypeControl" [matAutocomplete]="auto3">
    <mat-autocomplete #auto3="matAutocomplete" [displayWith]="displayFn" (optionSelected)='setClientTypeId($event.option.value)'>
        <mat-option *ngFor="let clientType of clientTypes" [value]="clientType">
            {{ clientType.Name }}
        </mat-option>
    </mat-autocomplete>
</mat-form-field>
<br>

当我使用编辑时,我从数据库中获取保存的 accountTypeId。我的问题在于如何将获取的 accounTypeId 作为默认选项放置到 matautocomplete 中,但仍然可以获得其余选项?

谢谢。

【问题讨论】:

标签: angular mat-autocomplete


【解决方案1】:

您可以通过以下两种方式之一实现此目的:

  1. 在 ts 文件中创建一个属性,并在 ngOnInit 上为其分配一个默认值,并在输入控件中使用模型绑定 [(ngModel)]="your property" 来设置默认值。
  2. 使用patchValues 并为ngOnInit 上的表单控件分配一个值。

【讨论】:

    猜你喜欢
    • 2020-08-08
    • 1970-01-01
    • 2020-10-25
    • 2021-10-30
    • 1970-01-01
    • 2012-02-25
    • 2022-01-09
    • 2017-02-18
    • 2018-05-15
    相关资源
    最近更新 更多