要将Angular FormArray与搜索框绑定,你可以按照以下步骤进行操作:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent implements OnInit {
searchForm: FormGroup;
items: FormArray;
constructor(private formBuilder: FormBuilder) { }
ngOnInit(): void {
this.searchForm = this.formBuilder.group({
searchInput: ''
});
this.items = this.formBuilder.array([]);
}
}
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent implements OnInit {
searchForm: FormGroup;
items: FormArray;
constructor(private formBuilder: FormBuilder) { }
ngOnInit(): void {
this.searchForm = this.formBuilder.group({
searchInput: ''
});
this.items = this.formBuilder.array([]);
this.searchForm.get('searchInput').valueChanges.subscribe(searchValue => {
this.filterItems(searchValue);
});
}
filterItems(searchValue: string): void {
const filteredItems = this.items.controls.filter((itemControl: FormGroup) => {
const itemName = itemControl.get('name').value.toLowerCase();
return itemName.includes(searchValue.toLowerCase());
});
this.items = this.formBuilder.array(filteredItems);
}
}
addItem(): void {
const newItem = this.formBuilder.group({
name: ''
});
this.items.push(newItem);
}
这就是将Angular FormArray与搜索框绑定的解决方法。通过监听搜索框的变化,并根据搜索框的值来过滤FormArray中的项,你可以实现动态更新显示的项。