要在Angular中使用FormArray实现在对象数组上进行嵌套ngFor,可以按照以下步骤进行操作:
import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
form: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit(): void {
this.form = this.fb.group({
items: this.fb.array([])
});
}
get items(): FormArray {
return this.form.get('items') as FormArray;
}
addItem(): void {
this.items.push(this.fb.group({
name: '',
age: ''
}));
}
removeItem(index: number): void {
this.items.removeAt(index);
}
}
addItem(): void {
this.items.push(this.fb.group({
name: '',
age: ''
}));
}
removeItem(index: number): void {
this.items.removeAt(index);
}
通过以上步骤,就可以实现在对象数组上使用FormArray进行嵌套ngFor的功能。