在表单数组中添加单选按钮时,上一个单选按钮会丢失数据角度


https://stackblitz.com/edit/angular-zm6qez?file=src%2Fapp%2Fapp.component.html

在表单数组中动态添加行时,我之前的单选按钮会丢失数据,但我的输入字段不会。但是在我的预标记表单上,json 值被我的 HTML 正确显示,没有显示

app.component.ts

`import { Component, OnInit } from '@angular/core';
import { FormGroup, FormArray, FormBuilder, Validators } from 
'@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent  implements OnInit{
name = 'Angular 6';
constructor(
private _form:FormBuilder
){    
}
public form:FormGroup;
ngOnInit(){
this.initializeForm();
}
public initializeForm(){
this.form = this._form.group({
itemRows : this._form.array([this.itemRows()]),
});   
}
public itemRows(){
return this._form.group({
name:["",[Validators.required]],
gender:["male",[Validators.required]]
});
}
public addRow(){    
const control = <FormArray>this.form.controls['itemRows'];
control.push(this.itemRows());
}
}`

app.component.html

`<form [formGroup]="form" novalidate>
<div formArrayName="itemRows">
<div class="row" 
*ngFor="let item of form.get('itemRows')['controls'];let i=index">
<div class="col-sm-12">
<div class="form-group"  [formGroupName]="i">
<label for="name_{{i}}">Name</label>
<input type="text" 
id="name_{{i}}" 
formControlName="name">
</div>
<div class="form-group"  [formGroupName]="i">
<label for="gender_{{i}}">Gender</label>
<input type="radio" id="gender_{{i}}" 
name="gender"
formControlName="gender"
value="male">Male
<input type="radio" id="gender_{{i}}" 
name="gender"
formControlName="gender"
value="Female">Female
</div>        
</div>
</div>
</div>
<div class="form-group">
<button class="button" 
(click)="addRow()">Add Fields</button>
</div>
<pre>
{{form.value | json}}
</pre>
</form>`

在我的 HTML pre 标记上清楚地显示输入的数据仍然存在,但我的 HTML 单选按钮显示为空白。

你可以试试这段代码

从输入无线电中删除name属性

<div class="form-group"  [formGroupName]="i">
<label for="gender_{{i}}">Gender</label>
<input type="radio" id="gender_{{i}}"
formControlName="gender"
value="male">Male
<input type="radio" id="gender_{{i}}"
formControlName="gender"
value="Female">Female
</div>  

我已经在堆栈闪电战上创建了演示

这是因为您将单选按钮的默认值"male"指定为"male",因此当您添加新的单选控件时,将选择该新控件的值。所以删除默认值"男性">

public itemRows(){
return this._form.group({
name:["",[Validators.required]],
gender:["",[Validators.required]]
});
}

分叉演示

最新更新