https://stackblitz.com/edit/angular-zm6qez?file=src%2Fapp%2Fapp.component.html
在动态添加表格数组中的行时,我之前的单选按钮会丢失数据,但我的输入字段却没有。但是在我的预标签表单上,我的HTML没有显示正确显示的json值
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预标签上清楚地显示数据输入数据是什么,但我的html单选按钮显示为空白。
答案 0 :(得分:1)
你可以试试这段代码
从输入广播
中删除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>
上创建了演示
答案 1 :(得分:0)
这是因为您将默认值设置为“男性”到单选按钮,因此当您添加新的无线电控件时,将选择该新控件的值。因此,删除默认值“男性”
public itemRows(){
return this._form.group({
name:["",[Validators.required]],
gender:["",[Validators.required]]
});
}
分叉Demo