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: ""}`       
});
2
  • refer this one may help you: stackoverflow.com/questions/38521648/… Commented Nov 5, 2018 at 8:51
  • so where's the problem? Instead of filter() you can use map() and change formObj to whatever you need. Commented Nov 5, 2018 at 9:29

1 Answer 1

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

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

1 Comment

Or you can use ' Object.keys(data).forEach((key) => (!data[key]) && delete data[key]);' if your values can be empty or 'null' or 'undefined'

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.