1

I have reactive form in angular application. I subscribe to it with valueChanges and before get the result of subscribe method, want to filter this object with rxjs filter or some similar method to get only not empty feald of form. How can I solve this?

this.form.valueChanges.pipe(
     debounceTime(500),
     filter(formObj => {
     // code that remove empty object values
     })
).subscribe(val => {
  // val example `{fullName: "name", dateOfBirthday: "", phoneNumber: "", fullAddress: ""}`       
});
Bogdan Tushevskyi
  • 712
  • 2
  • 12
  • 25

1 Answers1

3

Had created a Stackblitz Demo for your reference

You can somehow implement it like this:

filterEmptyFields(data: any): any {    // Filter any fields that aren't empty & store in a new object - To be passed on the Pipe map's caller
    let fields = {};
    Object.keys(data).forEach(key =>  data[key] != '' ? fields[key] = data[key] : key);

    return fields;   
}

trackEmptyFields(): void {
    this.form
      .valueChanges
      .pipe(map(this.filterEmptyFields))
      .subscribe(fields => console.log(fields));    
}

Output from the Stackblitz Demo

enter image description here

KShewengger
  • 7,853
  • 3
  • 24
  • 36
  • 1
    Or you can use ' Object.keys(data).forEach((key) => (!data[key]) && delete data[key]);' if your values can be empty or 'null' or 'undefined' – Bogdan Tushevskyi Nov 05 '18 at 13:56