1

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.

7
  • Can u provide a demo code on stackblitz.com ? Otherwise this will be closed Commented Sep 28, 2022 at 10:45
  • I have updated the question with that it logs. I dont think it is needed to make a stackblitz demo since it is just a clg Commented Sep 28, 2022 at 10:49
  • Why do you need it to be undefined? Commented Sep 28, 2022 at 11:05
  • It needs to be undefined because the object returned from the form gets sent to the backend transformed into a URL (like query params) and if the field is null, it transform it into literal string 'null', but if the field is undefined, it skips the field and doesn't append to the url. Commented Sep 28, 2022 at 11:08
  • Why you don't iterate through the keys of the final value and update the null to undefined before sending it to the BE? Commented Sep 28, 2022 at 11:10

1 Answer 1

2

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);

Sign up to request clarification or add additional context in comments.

1 Comment

While this may work for some people, I have a usecase where I have variables that can be null and others that can be undefined, and they should be treated differently. I don't like how Reactive Forms make this so difficult.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.