angular reactive form can't remove null item

Viewed 1931

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

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

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

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!

Related