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

Angular Material Select - default value selected from array

我关注angular material select HTML:

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

MOQALAQEdokumentisTipebi 是一个从网络 API 请求更新的数组。我只想 select 默认情况下 '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];

但在这种情况下,我变得一片空白 selection,就好像没有分配任何东西一样。我还控制台记录了我的 defValue 变量并显示了数据,但它在默认情况下不起作用 selection.

我的问题是如何在代码中设置默认 selection 数组的第一个元素(使用 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])
}