Search code examples
angulartypescriptangular-forms

Angular filter formArray controls based on some condition


I'm facing one issue I want to filter formArray controls

public checklistForm!: FormGroup;

 this.checklistForm = this.fb.group({
      checklistItems: this.fb.array([])
 });

// some logic

  public checklistItems(): FormArray {
    return this.checklistForm.get('checklistItems') as FormArray;
  }

// filter some checklistsItems
const newFormArray = this.checklistItems().value.filter(// some condition, may be check of id) //this return an array  

HTML

<div *ngFor="let checkList of checklistItems().controls; let checkListIndex=index"></div>

I'm not sure how can I filter this checklistItems().controls


Solution

  • We can just use the filter to store the values in a temporary variable, which we will use to run the *ngFor below is a working example, where I filter the form controls based on search.

    import { CommonModule } from '@angular/common';
    import { Component, inject } from '@angular/core';
    import {
      ReactiveFormsModule,
      FormArray,
      FormGroup,
      FormControl,
      FormBuilder,
    } from '@angular/forms';
    import { bootstrapApplication } from '@angular/platform-browser';
    import 'zone.js';
    
    @Component({
      selector: 'app-root',
      standalone: true,
      imports: [CommonModule, ReactiveFormsModule],
      template: `
      Search: <input #input (input)="search(input.value)"/>
      <form [formGroup]="checklistForm">
        <div formArrayName="checklistItems">
          <div *ngFor="let checkList of filteredCheckListItems; let checkListIndex=index" [formGroupName]="checkListIndex">
            {{checkListIndex}}
            <input type="text" [formControl]="checkList.controls.test" id="test" name="test"/>
          </div>
        </div>
      </form>
      {{checklistForm.value | json}}
      `,
    })
    export class App {
      fb = inject(FormBuilder);
      public checklistForm!: FormGroup;
      filteredCheckListItems: Array<any> = [];
    
      // some logica
    
      public checklistItems(): FormArray {
        return this.checklistForm.get('checklistItems') as FormArray;
      }
    
      ngOnInit() {
        this.checklistForm = this.fb.group({
          checklistItems: this.fb.array([]),
        });
        const checkListItems = this.checklistItems();
        checkListItems.push(this.fb.group({ test: new FormControl('apple') }));
        checkListItems.push(this.fb.group({ test: new FormControl('banana') }));
        checkListItems.push(this.fb.group({ test: new FormControl('grapes') }));
    
        // store the full unfiltered checklist items in the variable
        this.filteredCheckListItems = this.checklistItems().controls;
      }
    
      search(searchStr: string) {
        console.log(searchStr);
        this.filteredCheckListItems = (<Array<FormGroup>>(
          this.checklistItems().controls
        )).filter((item: FormGroup) => {
          return item?.controls?.['test']?.value?.includes(searchStr);
        });
      }
    }
    
    bootstrapApplication(App);
    

    Stackblitz Demo