【问题标题】:Angular Material Select - default value selected from arrayAngular Material Select - 从数组中选择的默认值
【发布时间】:2021-03-19 10:19:34
【问题描述】:

我有以下角度材料选择 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);
});

【问题讨论】:

  • 对您有帮助吗? stackoverflow.com/a/50651042/6444705
  • 值也不给选择,我试过了
  • 可能是使用数组作为选项和循环。在这种情况下,如何使工作默认值成为问题
  • 不要同时使用 ngModel 和 formControlName。仅使用表格。当你得到回复时,请this.form.get('personPersonDocumentTypes').patchValue(MOQALAQEdokumentisTipebi[0])
  • 但是如何设置默认选择值呢?如何在此处分配 -

标签: angular angular-material selection


【解决方案1】:

正如@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])
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-26
    • 1970-01-01
    • 2017-11-11
    • 1970-01-01
    • 2020-07-26
    相关资源
    最近更新 更多