gpt4 book ai didi

arrays - 在 Angular 中过滤表单数组

转载 作者:行者123 更新时间:2023-12-03 17:30:32 26 4
gpt4 key购买 nike

我有一个列表,我将其转换为 FormArray 以生成 html 中的按钮列表。我想按名称过滤汽车

CarComponent.html

  <input #searchBox id="search-box" (input)="search(searchBox.value)" />

<form [formGroup]="form" *ngIf="showCars">
<input type="button" class ="btn" formArrayName="carsList" *ngFor="let car of carsList$ | async; let i = index" value="{{carsList[i].name}}" >
</form>

CarComponent.ts
 carsList$: Observable<Car[]>;
private searchTerms = new Subject<string>();
search(term: string): void {
this.searchTerms.next(term);
}

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

this.addButtons();

}

ngOnInit() {
this.spinner.show();
this.carsList$ = this.searchTerms.pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap((term:string)=>
this.carsList ??? // Is this correct ?? What do I put here ?
)




}

private addButtons() {

this.carsList.map((o,i)=>{
const control = new FormControl;
(this.form.controls.carsList as FormArray).push(control);
})
}

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

所以我想知道如何正确进行过滤,而不是出于性能原因使用管道。

最佳答案

您可以使用数组 filter函数和数组 includes过滤掉 FormArray 中的值或 Array .

const CarsList = [
{ name: 'Mercedes' },
{ name: 'BMW' },
{ name: 'Porsche' },
{ name: 'Cadillac' }
];
const result = CarsList.filter(s => s.name.includes('Mercedes'));

console.log(result);

关于arrays - 在 Angular 中过滤表单数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55082191/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com