我们只需使用过滤器将值存储在临时变量中,我们将使用该变量来运行下面的*ngFor
(这是一个工作示例),其中我根据搜索过滤表单控件
如果有任何疑问请告诉我!
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