微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Angular Material Select - 从数组中选择的默认值

如何解决Angular Material Select - 从数组中选择的默认值

我有以下角度材料选择 HTML:

<mat-select formControlName='personPersonDocumentTypes'>
<mat-option *ngFor="let dokumeti of MOQALAQEdokumentisTipebi" [value]="dokumeti">
{{dokumeti}}
</mat-option>
</mat-select>

MOQALAQEdokumentisTipebi 是一个从网络 API 请求更新的数组。我只想认选择“MOQALAQEdokumentisTipebi”数组的第一个元素。

我试过做这样的事情:

<mat-select [(ngModel)]="MOQALAQEdokumentisTipebi[0]" formControlName='personPersonDocumentTypes'>
<mat-option *ngFor="let dokumeti of MOQALAQEdokumentisTipebi" [value]="dokumeti">
{{dokumeti}}
</mat-option>
</mat-select>

在这种情况下,我会得到整个数组而不是第一个元素。

我尝试在我的 TS 文件添加认变量:

public defValue = MOQALAQEdokumentisTipebi[0];

在这种情况下,我得到了空白选择,好像没有分配给它。我还控制台记录了我的 defValue 变量并显示了数据,但它在认选择中不起作用。

我的问题是如何在这样的代码中设置数组的认选择第一个元素(使用 ngFor):

<mat-select formControlName='personPersonDocumentTypes'>
<mat-option *ngFor="let dokumeti of MOQALAQEdokumentisTipebi" [value]="dokumeti">
{{dokumeti}}
</mat-option>
</mat-select>

// 添加文档类型数组


this.moqalaqeSearchData.personPersonDocumentTypes.map((array) => {
this.MOQALAQEdokumentisTipebi.push(array.personDocumentType.nameGeorgian);
});

解决方法

正如@Bojan 所说,接收数据时需要设置表单值:

form: FormGroup;

constructor() {
  this.form = new FormGroup({
    personPersonDocumentTypes: [''],// ...
  });

  this.moqalaqeSearchData.personPersonDocumentTypes.map((array) => {
    this.MOQALAQEdokumentisTipebi.push(array.personDocumentType.nameGeorgian);
  });

  this.form.get('personPersonDocumentTypes').patchValue(this.MOQALAQEdokumentisTipebi[0])
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。