角度过滤器表单基于某些条件的数组控件

问题描述 投票:0回答:1

我面临一个问题,我想过滤 formArray 控件

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>

我不知道如何过滤这个

checklistItems().controls

angular typescript angular-forms
1个回答
1
投票

我们可以使用过滤器将值存储在临时变量中,我们将用它来运行下面的

*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 演示

© www.soinside.com 2019 - 2024. All rights reserved.