我正在Angular 7应用程序中通过JSON创建动态表单。我从API获取JSON。然后,我将创建一个与我的动态表单JSON匹配的新JSON对象。然后,我通过它来创建视图。但我收到错误TypeError:无法读取null的“有效”属性 在Object.eval [作为updateDirectives]问题。但是我在将数据传递到映射对象之前检查了null。有人可以帮我这个忙。我也想得到“这个物品是给谁的?”在我认为的主标签中(我在这里没有尝试过)可以有人帮助我解决此问题。这就是我尝试过的。
我的json就是这样
{
"id": 1000,
"question": "Who is this item for?",
"type": "Multiple",
"required": true,
"answers": [
{
"id": 100001,
"type": "radio",
"answer": "Me",
"nextQuestion": 1001,
"extendedFields": []
},
{
"id": 100002,
"type": "radio",
"answer": "For my parents",
"nextQuestion": 1001,
"extendedFields": []
}
]
}
我在json之上取得了如下结果。然后,我将JSON对象传递给方法。通过这种方法,我正在创建一个新的JSON数组,该数组正在传递以创建动态视图。
getData(){
return this.apiService.get("/Quiz/id/1000" ,true).subscribe(
(data: any) => {
if(!data){
this.mapData(data);
}
},
error => {
}
);
}
mapdata方法如下
mapData(obj) {
for (var i in obj.answers) {
var item = obj.answers[i];
this.dataList.push({
controlType: 'input',
label: item.answer,
key: item.answer
});
}}
我的动态视图HTML如下(form-control.component.html)
<div [formGroup]="parentForm">
<label [attr.for]="data.key">{{data.label}}</label>
<input *ngIf="data.controlType === 'input'" [formControlName]="data.key" [type]="data.type">
<select *ngIf="data.controlType === 'select'" [formControlName]="data.key">
<option disabled [selected]="true">Please select {{ data.whatToSelect}}</option>
<option *ngFor="let selectOption of data.selectOptions" [value]="selectOption.value">{{selectOption.value}}</option>
</select>
<div *ngIf="data.controlType === 'radio'">
<label *ngFor="let opt of data.options">
{{opt.key}}
<input [value]="data.value" [type]="radio" [formControlName]="data.key">
</label>
</div>
</div>
form-control.component.ts
control: AbstractControl;
@Input() data: any;
@Input() parentForm: FormGroup;
ngOnInit() {
this.control = this.parentForm.get(this.data.key);
}
Form-main.component.ts
exampleForm: FormGroup;
showFormValue = false;
@Input() dataList: any[];
ngOnInit() {
const formContent: any = {};
this.dataList.forEach(data => {
formContent[data.key] = new FormControl(data.value, data.syncValidators, data.asyncValidators);
});
this.exampleForm = new FormGroup(formContent);
}
Form-main component.html
<form [formGroup]="exampleForm" (ngSubmit)="onSubmit()">
<app-form-control *ngFor="let data of dataList" [data]="data" [parentForm]="exampleForm"></app-form-control>
<button type="button" (click)="onReset()">Reset</button>
</form>
</div>