在使用Angular 12中的FormControls时,可以在内嵌两个FormArrays的formGroup中使用。以下是具体的代码示例:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
@Component({
selector: 'app-nested-form-array',
templateUrl: './nested-form-array.component.html',
styleUrls: ['./nested-form-array.component.css']
})
export class NestedFormArrayComponent implements OnInit {
myForm: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.myForm = this.fb.group({
customers: this.fb.array([
this.fb.group({
name: '',
orders: this.fb.array([
])
})
])
});
this.addOrder();
}
get customers() {
return this.myForm.get('customers') as FormArray;
}
get orders() {
return this.customers.controls[0].get('orders') as FormArray;
}
addOrder() {
this.orders.push(this.fb.group({
product: '',
quantity: ''
}));
}
}
Name:
Product:
Quantity:
在以上示例代码中,我们创建了一个FormGroup,并在其内部嵌套了两个FormArray,分别为“customers”和“orders”