我正在为我的应用程序创建“编辑视图”,我从API调用中接收信息,然后使用补丁将这些值设置为表单。我在选择下拉菜单时遇到了一些主要问题,因为补丁值似乎没有放入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"],
...
}
答案 0 :(得分:0)
我在项目中使用了这种方法。
Apache Livy
修补时,它将自动修补您的值
解决方案2:
您可以通过
选择数据或ID。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>
实时示例:stackblitz
答案 1 :(得分:0)
使用此:-
this.initRequests().then((data) => {
const keys = Object.keys(data);
const patchValueData = {};
keys.forEach(function(key) {
patchValueData[key] = k[key][0]
});
this.userDetailsForm.patchValue(patchValueData)
});