繁体   English   中英

角度-使用补丁在下拉菜单中设置选定的值

[英]Angular - Set selected value in dropdown using patch

我正在为我的应用程序创建“编辑视图”,我从API调用中收到信息,然后使用patch将这些值设置为表单。 我在选择下拉菜单时遇到了一些主要问题,因为补丁值似乎没有放入API的默认值。 将数据从我的API绑定到我的选择中的正确方法是什么?

我搜索了与我类似的问题,发现需要设置ngModel,我尝试在选项中选择标签,但它也不起作用。

选择标签(HTML)

<mat-grid-tile>
    <p class="input-ref mandatory">Industry Type</p>
    <mat-form-field class="full-width" appearance="outline" [floatLabel]="'always'">
        <mat-label>Industry Type</mat-label>
        <mat-select placeholder="" formControlName="IndustryType2">
            <mat-option *ngFor="let industryType2 of industryTypes" [value]="industryType2">
{{ industryType2 }}
            </mat-option>
        </mat-select>
    </mat-form-field>
</mat-grid-tile>

行业类型选项(始终是静态的)

industryTypes = [
        '(MH)',
        '(HS)',
        '(CM)',
        '(HL)',
        '(IS)'
    ];

我使用FormBuild创建表单,然后使用API​​调用填充表单

// CREATE FORMS
this.userDetailsForm = this.fb.group({
    IndustryType2: ['']
})

// POPULATE FORMS
this.initRequests().then((data) => {
    this.userDetailsForm.patchValue(data)
})

这是我从API收到的JSON响应

{
    IndustryType2: ["(MH)"],
    OtherProperty: ["Example"],
    ...
}

我在项目中使用了这种方法。

this.form = this.fb.group({
  IndustryType2: this.fb.group({
    id: ['']
  });
});

<mat-form-field class="full-width" formGroupName="IndustryType2"  appearance="outline" [floatLabel]="'always'">
  <mat-label>Industry Type</mat-label>
  <mat-select placeholder="" formControlName="id">
    <mat-option *ngFor="let industryType2 of industryTypes" [value]="industryType2">
      {{ industryType2 }}
    </mat-option>
  </mat-select>
</mat-form-field>

修补时,它将自动修补您的价值

解决方案2:

您可以通过选择数据或ID

form.get('controlname').setValue(res.id);

现场示例: stackblitz

用这个:-

   this.initRequests().then((data) => {
        const keys = Object.keys(data);
        const patchValueData = {};
        keys.forEach(function(key) {
        patchValueData[key] = k[key][0]
        });
        this.userDetailsForm.patchValue(patchValueData)
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM