5

I try to use the reactive form and I need to create only the key for each item that is filled But because the first moment is created, if the field is not full, it sends null While I want a field that is not empty to be sent at all my code is:

form: FormGroup;
 constructor() {
    this.form = new FormGroup({
      basePrice: new FormControl(null, [customeValidator.numberOnly()]),
      discountValue: new FormControl(null, [customeValidator.numberOnly()]),
      roomViewCount: new FormControl(null, [customeValidator.numberOnly()])
    });
  }


onCalcute() {
    console.log(this.form.value);

    if (this.form.valid) {
      this.roomData = {
        basePrice: this.form.value.basePrice,
        discountValue: this.form.value.discountValue,
        roomViewCount: this.form.value.roomViewCount
      };
      this.clicked = true;
    }
  }

if just one of them was full console.log return

{
        basePrice: 20,
        discountValue: null,
        roomViewCount: null
}

but I need:

{
        basePrice: 20
}

3 Answers 3

2

You can filter null values in submit function:

onSubmit() {
    const filtered = {};
    if (this.form.valid) {
      for (let key in this.form.value) {
        if (this.form.value[key]) {
          filtered[key] = this.form.value[key];
        }
      }
      console.log(filtered);
    }
  }

DEMO

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

2 Comments

So where should add my validation? in your sample code there is no validation
@heliyaRahbar for numberOnly validation you can use something like this: basePrice = new FormControl(null, Validators.pattern("^[0-9]*$")); that validates null value.
2

You could do this just in a single line before submitting, as like this:

Object.keys(this.form).forEach((key) => (this.form[key] == null) && delete this.form[key]);

It's simplest & more intelligent!

Comments

1

You can use JAVASCRIPT logic Like.

first bind all values in one variable.

const formValues = this.form.value; 
console.log('Result before remove null', formValues);

Then make another variable for Object key and use for loop to remove null values.

const formKeys = Object.keys(formValues);
if(formKeys.length){
    for(let i = 0; i < formKeys.length; i++){
      if(formValues[formKeys[i]] === null || formValues[formKeys[i]] === undefined){
         delete formValues[formKeys[i]];
       }
     }
   }

console.log('Result', formValues);

Here is stackblitz demo: https://stackblitz.com/edit/angular-ivy-eq5d9a

1 Comment

If you vote down answer or question, Give your reason. So we understand what is wrong in answer or question.

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.