How to filter through a FormArray using Pipe in Angular to search for specific value?

651 views Asked by At

I have a following object as formArray that I am passing inside of the transform method in my pipe.ts file. The object looks as following

enter image description here

I want to access the value property of said object, where the firstName and lastName are stored. I want to filter it by those first and last name to search for a specific user inside of that FormArray

enter image description here

I have the following in my pipe ts file, which is referenced in the html file displaying those names and email address.

export class FilterPipe implements PipeTransform {
  transform(nameData: FormArray, searchData:string) : FormArray{


    if(searchData === ""){
      return nameData;
  }
    var arrayForms = nameData.value;
    for(var element of arrayForms){
      if(element.valid){
        return arrayForms.filter((arrayForm)=> {
          return arrayForm.value.firstName.includes(searchData);
        })
      }
    }   
 }

at first I tried just using .filters to filter through, but I get error saying filter is not available for FormArray, so I tried converting the formArray into a regular array, but doing that, when debugging my nameData.value comes up as invalid, making the whole code block useless. I was expecting the filter to at first filter through the firstName property of the array

1

There are 1 answers

1
peinearydevelopment On

The FormArray type has a controls property on it which is of type AbstractControl[]. You should be able to utilize that to look into the values you want and filter accordingly. Something as follows.

nameData.controls.filter(control => control.valid && control.value.firstName.includes(searchData));

Its hard to give a full answer based on the limited information you gave above. If this code doesn't work exactly for you, providing an MVP in a StackBlitz example would help you solve your exact problem.