我正在尝试根据要求动态生成表单,但它给出了一个错误,表明无法使用路径找到控件:
在这里,我根据该列表从 API 获取列表我正在尝试动态生成复选框并将它们添加到 formgroup 但它给出了错误,请参阅下面的相同代码
这是组件的代码:
export class QualificationExpComponent implements OnInit {
jobmasterList: any = [];
checkboxform1: FormGroup;
public jobcount = 0;
constructor(private formBuilder: FormBuilder, private callapi: ServiceService, private _router: Router) { }
ngOnInit(): void {
this.addCheckboxes();
this.initializecheckboxform1();
this.callapi.getDetails().subscribe(res => {
if (res.data !== null) {
this.jobmasterList = res.data.jobs;
this.categoriesList = res.data.jobs[0].category;
this.subcatList = res.data.jobs[0].category[0].sub_category;
console.log(this.subcatList)
}
})
}
}
initializecheckboxform1() {
this.checkboxform1 = this.formBuilder.group({
orders: new FormArray([], this.minSelectedCheckboxes(1))
});
}
minSelectedCheckboxes(min = 1) {
const validator: ValidatorFn = (formArray: FormArray) => {
const totalSelected = formArray.controls
// get a list of checkbox values (boolean)
.map(control => control.value)
// total up the number of checked checkboxes
.reduce((prev, next) => next ? prev + next : prev, 0);
// if the total is not greater than the minimum, return the error message
return totalSelected >= min ? null : { required: true };
};
return validator;
}
get ordersFormArray() {
return this.checkboxform1.controls.orders as FormArray;
}
private addCheckboxes() {
this.jobmasterList.forEach(() => this.ordersFormArray.push(new FormControl(false)));
}
get sf() {
return this.salaryexpForm.controls;
}
get rf() {
return this.remunerationForm.controls;
}
SelectePrevExperience() {
const selectedOrderIds = this.checkboxform1.value.orders
.map((v, i) => v ? this.jobmasterList[i].id : null)
.filter(v => v !== null);
console.log(selectedOrderIds);
console.log(this.checkboxform1.value);
}
checkboxform1submit() {
console.log(this.checkboxform1.value);
}
}
这是我试图用 formControlName 绑定数据的 HTML 组件:
<span formArrayName="orders" *ngFor="let master of jobmasterList; let i = index">
<div *ngIf="i === jobcount">
<span class="TextMaroonBold" style="color: #1c8bea;font-weight: bold;"> {{master.description}}
</span><br>
<span *ngFor="let order of master.category; let j = index">
<input type="text" value="{{order.category_id}}" [formControlName]="j" style="display: none;">
<span class="TextMaroonBold"> {{order.name}}
</span>
<div class="ex1">
<span *ngFor="let option of order.sub_category; let k = index" class="checkbox">
<div class="form-check" style="padding-left: 35px;">
<input type="checkbox" value="{{option.ref_id}}" [formControlName]="k">
{{option.name}}
</div>
</span>
</div>
</span>
</div>
</span>
在控制台中,我看到以下错误:
ERROR Error: Cannot find control with path: 'orders -> i'