我目前正在使用一個表單組件,Reactive Forms并且Angular13 .
我已經設定了表單并且它正在正常作業,但是我有一個問題我找不到解決方案。
我發布了表單的代??碼。
form.component.ts:
this.myForm= this.fb.group({
input1: new FormControl(),
input2: new FormControl(),
input3: new FormControl(),
input4: new FormControl(),
input5: new FormControl(),
});
如您所見,不需要任何輸入,因此用戶可以填寫或不填寫輸入欄位。
當我想傳遞回傳表單 ( console.log(form)) 的物件時,我的問題出現了,如果任何輸入欄位未填寫,它會回傳,null但我需要回傳undefined。
有沒有辦法做到這一點?
編輯:
我粘貼表單回傳的內容console.log()
input1: null
input2: null
input3: 'some data'
input4: null
當輸入欄位被填充時,它回傳提供的資料,但當它沒有被填充時,它回傳null。
uj5u.com熱心網友回復:
您可以通過在將表單的值發送到 BE 之前對其進行映射來實作這一點,如下所示:
export function getMappedValue<T>(value: T): T {
return Object.keys(value).reduce((acc, curr) => {
if (value[curr] !== null) {
acc[curr] = value[curr];
}
return acc;
}, {} as T);
}
//...
// Then we can use it in the component before sending the value to BE:
const valueToBeSent = getMappedValue(this.myForm.value);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/510213.html
標籤:有角度的打字稿角反应形式
上一篇:我怎樣才能在rxjs中捕獲成功的回應并回傳一些特定的值?
下一篇:RxJSfrom()和陣列
