在 Angular 中过滤表单数组

问题描述 投票:0回答:1
arrays angular forms typescript formarray
1个回答
0
投票

出于性能原因,要在不使用管道的情况下过滤汽车列表,您可以直接过滤组件代码中的数组。

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, FormArray } from '@angular/forms';
import { Observable, Subject } from 'rxjs';
import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';

interface Car {
  name: string;
}

const CarsList: Car[] = [
  { name: 'Mercedes' },
  { name: 'BMW' },
  { name: 'Porsche' },
  { name: 'Cadillac' }
];

@Component({
  selector: 'app-car',
  templateUrl: './car.component.html',
  styleUrls: ['./car.component.css']
})
export class CarComponent implements OnInit {
  form: FormGroup;
  carsList$: Observable<Car[]>;
  showCars = true;

  private searchTerms = new Subject<string>();

  constructor(private formBuilder: FormBuilder) {
    this.form = this.formBuilder.group({
      carsList: new FormArray([])
    });
  }

  ngOnInit() {
    this.addButtons();

    this.carsList$ = this.searchTerms.pipe(
      debounceTime(300),
      distinctUntilChanged(),
      switchMap((term: string) => {
        return this.filterCars(term);
      })
    );
  }

  private addButtons() {
    CarsList.forEach((car: Car) => {
      const control = new FormControl();
      (this.form.controls.carsList as FormArray).push(control);
    });
  }

  private filterCars(term: string): Observable<Car[]> {
    const filteredCars = CarsList.filter((car: Car) =>
      car.name.toLowerCase().includes(term.toLowerCase())
    );
    return new Observable<Car[]>(subscriber => {
      subscriber.next(filteredCars);
      subscriber.complete();
    });
  }

  search(term: string): void {
    this.searchTerms.next(term);
  }
}

在上面的代码中,我们删除了

carsList
observable,而是直接使用
CarsList
数组。然后实现
filterCars
方法来根据搜索词过滤汽车。在
ngOnInit
中,我调用
addButtons
用每辆车的按钮填充表单数组。并且 search 方法用于当用户在搜索框中输入文本时触发搜索。

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