gpt4 book ai didi

angular - 何时使用 FormGroup 与 FormArray?

转载 作者:太空狗 更新时间:2023-10-29 16:45:56 27 4
gpt4 key购买 nike

FormGroup :

A FormGroup aggregates the values of each child FormControl into oneobject, with each control name as the key.

const form = new FormGroup({
first: new FormControl('Nancy', Validators.minLength(2)),
last: new FormControl('Drew')
});

FormArray :

A FormArray aggregates the values of each child FormControl into anarray.

const arr = new FormArray([
new FormControl('Nancy', Validators.minLength(2)),
new FormControl('Drew')
]);

什么时候应该用一个代替另一个?

最佳答案

FormArray 是 FormGroup 的变体。关键区别在于它的数据被序列化为一个数组(而不是在 FormGroup 的情况下被序列化为一个对象)。当您不知道组中将存在多少控件时(例如动态表单),这可能特别有用。

让我试着通过一个简单的例子来解释。比方说,您有一个表单,您可以在其中捕获客户的比萨饼订单。然后你放置一个按钮让他们添加和删除任何特殊请求。这是组件的 html 部分:

<section>
<p>Any special requests?</p>
<ul formArrayName="specialRequests">
<li *ngFor="let item of orderForm.controls.specialRequests.controls; let i = index">
<input type="text" formControlName="{{i}}">
<button type="button" title="Remove Request" (click)="onRemoveSpecialRequest(i)">Remove</button>
</li>
</ul>
<button type="button" (click)="onAddSpecialRequest()">
Add a Request
</button>
</section>

这里是定义和处理特殊请求的组件类:

constructor () {
this.orderForm = new FormGroup({
firstName: new FormControl('Nancy', Validators.minLength(2)),
lastName: new FormControl('Drew'),
specialRequests: new FormArray([
new FormControl(null)
])
});
}

onSubmitForm () {
console.log(this.orderForm.value);
}

onAddSpecialRequest () {
this.orderForm.controls
.specialRequests.push(new FormControl(null));
}

onRemoveSpecialRequest (index) {
this.orderForm.controls['specialRequests'].removeAt(index);
}

FormArray 提供了比 FormGroup 更大的灵 active ,因为使用“push”、“insert”和“removeAt”比使用 FormGroup 的“addControl”、“removeControl”、“setValue”等更容易操作 FormControls。FormArray 方法确保在表单的层次结构中正确跟踪控件。

希望这对您有所帮助。

关于angular - 何时使用 FormGroup 与 FormArray?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41288928/

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