在 Angular 9 中,你可以使用对象数组来获取表单数据。以下是实现这一功能的步骤:
FormGroup
或 FormArray
。假设我们有一个简单的表单,用户可以添加多个地址记录。
<form [formGroup]="addressForm">
<div formArrayName="addresses">
<div *ngFor="let address of addresses.controls; let i = index" [formGroupName]="i">
<input formControlName="street" placeholder="Street">
<input formControlName="city" placeholder="City">
<button type="button" (click)="removeAddress(i)">Remove</button>
</div>
</div>
<button type="button" (click)="addAddress()">Add Address</button>
</form>
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, Validators } from '@angular/forms';
@Component({
selector: 'app-address-form',
templateUrl: './address-form.component.html',
styleUrls: ['./address-form.component.css']
})
export class AddressFormComponent implements OnInit {
addressForm: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit(): void {
this.addressForm = this.fb.group({
addresses: this.fb.array([])
});
}
get addresses() {
return this.addressForm.get('addresses') as FormArray;
}
addAddress(): void {
const addressGroup = this.fb.group({
street: ['', Validators.required],
city: ['', Validators.required]
});
this.addresses.push(addressGroup);
}
removeAddress(index: number): void {
this.addresses.removeAt(index);
}
}
formControlName
和 formGroupName
。addAddress
方法中正确创建和添加 FormGroup
到 FormArray
。removeAddress
方法中正确删除指定索引的 FormGroup
。通过以上步骤和示例代码,你应该能够在 Angular 9 中使用对象数组获取表单数据。如果遇到具体问题,请提供更多详细信息以便进一步诊断。
领取专属 10元无门槛券
手把手带您无忧上云