下面是组件代码
bedsArray: Array<{displayText: string, bed: number}> = [];
roomCount = 3; // This is not fixed.
roomForm: FormGroup;
ngOnInit() {
this.bedsArray.push({bed: 1, displayText: '1 Bed'});
this.bedsArray.push({bed: 2, displayText: '2 Beds'});
this.bedsArray.push({bed: 3, displayText: '3 Beds'});
this.roomForm = new FormGroup({
rooms: this.genRoomArray(),
buildingName: new FormControl('Building 1')
});
}
genRoomArray(): FormArray {
const roomsArray = new FormArray([]);
for(let i = 0; i < this.roomCount; i++) {
const roomGroup = new FormGroup({
roomNo: new FormControl('', Validators.required),
bedsCount: new FormControl('', Validators.required)
});
roomsArray.push(roomGroup);
}
return roomsArray;
}
和模板代码
<form [formGroup]="roomForm">
<h3> {{ roomForm.get('buildingName').value }} Rooms </h3>
<div class="rooms" formArrayName="rooms">
<div class="room" style="padding: 2rem; border:1px solid gray; margin-
bottom:1rem;" *ngFor="let room of roomForm.get('rooms').controls"
[formGroup] = "room">
Room Number: <input type="text" formControlName="roomNo">
<div class="beds">
<div class="bed" *ngFor="let bed of bedsArray" [formGroup] = "room">
<input [value] = "bed.bed" name="bedsCount" formControlName="bedsCount" type="radio">
{{ bed.displayText }}
</div>
</div>
</div>
</div>
</form>
单选按钮无法正常工作。只有一个单选按钮被选中。
单选按钮的html名称应不同,以使其正常工作。 我该怎么做。
答案 0 :(得分:0)
所以您的模板几乎是正确的,我们需要一个动态的id
而不是name
,因此以下一些小的更改(在注释中)也消除了噪音,仅为了答案:
<form [formGroup]="roomForm">
<div formArrayName="rooms">
<div *ngFor="let room of roomForm.get('rooms').controls" [formGroup]="room">
Room Number: <input type="text" formControlName="roomNo">
<!-- You can remove formgroup from below div -->
<!-- add index so we have a dynamic index for id -->
<div *ngFor="let bed of bedsArray; let i = index">
<input [value]="bed.bed" [id]="i" formControlName="bedsCount" type="radio">
{{ bed.displayText }}
</div>
</div>
</div>
</form>