0

I am using Angular Reactive Form as shown below

  'storeName': [''],
  'statusId': [''],
  'storeAddress': this._formBuilder.group({
    'address': [''],
    'county': [''],
    'landmark': [''],
  }),

When I submit the form, for empty controls I still get field with empty string.

Is it possible to get the final value object with only those fields which contain some value in it?

Varun Sukheja
  • 6,170
  • 5
  • 51
  • 93

1 Answers1

0
  getNotNull(data:any):any
  {
    let notNull={}
    for (let key in data) {
      if (Array.isArray(data[key])) {
        let tmpArray=[]
        for (let i = 0; i < data[key].length; i++)
        {
          let tmp=this.getNotNull(data[key][i])

          if (typeof(tmp)!='object' || Object.keys(tmp).length)
            tmpArray.push(tmp)
        }
        if (tmpArray.length)
           notNull[key]=tmpArray;
      }
      else {
        if (typeof (data[key]) == "object")
        {
          let tmp=this.getNotNull(data[key]);
          if (typeof(tmp)!='object' || Object.keys(tmp).length)
            notNull[key]=tmp
        }
        else
        {
          if (data[key] || data[key]===0) //if you want to save 0 value
            notNull[key]=data[key]
        }
      }
    }
    return notNull
  }
Eliseo
  • 50,109
  • 4
  • 29
  • 67