In this scenario, utilizing the filter method allows us to save values in a temporary variable that can be employed to execute the *ngFor
as demonstrated in the code snippet below. The example showcases filtering form controls based on a search query.
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> = [];
// additional logic
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 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);
Check out the Stackblitz Demo