我尝试按照以下示例使用Reactive表单首次构建控件: https://coryrylan.com/blog/creating-a-dynamic-checkbox-list-in-angular
最终,我将使用服务,但是现在,我可以通过遵循代码来创建复选框。但是,在尝试创建单选按钮时,却不断出现-ERROR TypeError:无法读取未定义的属性'controls'。 我在做什么错了?
这是我在组件中的代码:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, FormControl, ValidatorFn } from '@angular/forms';
@Component({
selector: 'app-report',
templateUrl: './report.component.html',
styleUrls: ['./report.component.scss']
})
export class ReportComponent {
form: FormGroup;
orders = [
{ id: 100, name: 'chk 1' },
{ id: 200, name: 'chk 2' },
{ id: 300, name: 'chk 3' },
{ id: 400, name: 'chk 4' }
];
streams = [
{ id: 1, name: 'radio 1' },
{ id: 2, name: 'radio 2' }
];
tmp: boolean = false;
constructor(private formBuilder: FormBuilder) {
// Create a new array with a form control for each order
const controls = this.orders.map(c => new FormControl(false));
controls[0].setValue(true); // Set the first checkbox to true (checked)
// updated code
//for radio button
const controlsR = this.streams.map(c => new FormControl(false));
controls[0].setValue(true); // Set the first option to selected
this.form = this.formBuilder.group({
orders: new FormArray(controls),
streams: new FormArray(controlsR)
});
//this.form.addControl.name(controlsR);
//this.form = this.formBuilder.group({
// streams: new FormArray(controls)
//});
}
submit() {
const selectedOrderIds = this.form.value.orders
.map((v, i) => v ? this.orders[i].id : null)
.filter(v => v !== null);
console.log(selectedOrderIds);
}
}
和模板:
<form [formGroup]="form" (ngSubmit)="submit()">
<div class="cb-wrapper" [ngClass]="{'cb-vertical':!tmp}">
<label formArrayName="orders" *ngFor="let order of form.controls.orders.controls; let i = index">
<input type="checkbox" [formControlName]="i">
{{orders[i].name}}
</label>
</div>
<!--radio button-->
<!--updated code-->
<label formArrayName="streams" *ngFor="let stream of form.controls.streams.controls; let i = index">
<input type="radio" [formControlName]="i">
{{streams[i].name}}
</label>
<!-- <label formArrayName="streams" *ngFor="let stream of form.controls.streams.controlsR; let i = index">
<input type="radio" [formControlName]="i">
{{streams[i].name}}
</label>-->
<div *ngIf="!form.valid">At least one order must be selected</div>
<button>submit</button>
</form>