I am currently working on a form component using Reactive Forms
and Angular13 .
I have already set the form and it is working like it should, but I have a problem I can not find a solution.
I post the code for the form.
form.component.ts:
this.myForm= this.fb.group({
input1: new FormControl(),
input2: new FormControl(),
input3: new FormControl(),
input4: new FormControl(),
input5: new FormControl(),
});
As you can see, none of the inputs are required, so the user can either fill up the input field or not.
My problem comes when I want to pass the object that returns the form (console.log(form)
), if any of the input fields is not filled, it returns null
but I need to return undefined
.
Is there a way to do it?
EDIT:
I paste what the form returns when I do console.log()
input1: null
input2: null
input3: 'some data'
input4: null
When the input field is filled, it returns with the data provided, but when it is not filled, it returns null.
CodePudding user response:
You can achieve that by mapping the form's value before sending it to the BE, like the following:
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);
CodePudding user response:
I am not sure, but try this:
input: new FormControl<string | undefined>(undefined, {nonNullable: true})