gpt4 book ai didi

angular - 嵌套 formGroup 将对象绑定(bind)到单选按钮

转载 作者:行者123 更新时间:2023-12-02 10:13:30 31 4
gpt4 key购买 nike

我有嵌套的 formGroup:

  this.form = fb.group({
productName: ['ASD'],
productWeightCategory: fb.group({
id: [],
categoryWeightName: []
})

和模板:

<form class="container col-md-2" [formGroup]="form"
(ngSubmit)="onSubmit(form.value)">

<div>
<label for="productName">productName</label> <input
class="form-control" id="productName" type="text" placeholder=""
formControlName="productName"> <span class="small help-block"></span>
<label for="radios">weigh category</label>
<fieldset formGroupName="productWeightCategory">
<div class="radio"
*ngFor="let element of productWeightCategory; let ind=index;">
<label> <input [value]="element" type="radio" name="id"
[checked]="ind===0"> {{element.categoryWeightName}} index
= {{ind}}
</label>
</div>
</fieldset>
</div>
<input class="btn btn-primary" type="submit" [disabled]="!form.valid"
value="submit">
</form>

而且我无法从 radio 中获取值(value)。

可能我错过了一些东西,但我不知道是什么。

工作中demo

最佳答案

正如 Christian 建议的那样,删除嵌套组,您想要的是表单控件。如果您希望选择数组中的第一项,只需在构建表单时进行设置:

productWeightCategories = [
new ProductWeightCategory(1, 'value 1'),
new ProductWeightCategory(2, 'value 2'),
new ProductWeightCategory(3, 'value 3')
];

constructor(fb: FormBuilder) {
this.form = fb.group({
productName: ['ASD'],
productWeightCategory: [this.productWeightCategories[0]]
});
}

如果您想稍后设置它,请按照 Christian 的建议使用 setValue

对于您的模板,请像您一样使用[value],并使用formControlName="productWeightCategory"。您还需要将 name 属性更改为相同的,否则 Angular 将开始提示:)

<fieldset>
<div class="radio" *ngFor="let element of productWeightCategories; let i=index;">
<label>
<input [value]="element" type="radio"
name="productWeightCategory"
formControlName="productWeightCategory">
{{element.categoryWeightName}} index = {{i}}
</label>
</div>
</fieldset>

您的 StackBlitz

关于angular - 嵌套 formGroup 将对象绑定(bind)到单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47998824/

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