[英]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.