我遇到了动态表单的问题,尽管预言说它们是表单的一部分,并且填充了配置,但无法正确显示。
我的组件正在从服务中检索表单输入列表。
import { Component, OnInit, ViewChild } from '@angular/core';
import { DynamicFormComponent } from '@/_forms/dynamic-form/dynamic-form.component';
import { FieldConfig } from '@/_interface/field.interface';
import { QAndAService } from '@/_services/q-and-a.service';
@Component({
selector: 'app-dynamic-bedroom',
templateUrl: './dynamic-bedroom.component.html',
styleUrls: ['./dynamic-bedroom.component.css']
})
export class DynamicBedroomComponent implements OnInit {
@ViewChild(DynamicFormComponent) form: DynamicFormComponent;
regConfig: FieldConfig[];
constructor(private qandaService: QAndAService) {}
ngOnInit() {
this.getQuestions();
}
private getQuestions() {
this.qandaService.getQuestions().subscribe((resp: any) => {
this.regConfig = <FieldConfig[]> resp;
});
}
submit(value: any) { }
}
控制台日志报告该表单。值未定义。
错误TypeError:无法读取未定义的属性“值” 在DynamicFormComponent.get [作为值]处(dynamic-form.component.ts:21) 在Object.eval [作为updateRenderer](DynamicBedroomComponent.html:3) 在Object.debugUpdateRenderer [作为updateRenderer](core.js:22503) 在checkAndUpdateView(core.js:21878) 在callViewAction(core.js:22114) 在execComponentViewsAction(core.js:22056) 在checkAndUpdateView(core.js:21879) 在callViewAction(core.js:22114) 在execComponentViewsAction(core.js:22056) 在checkAndUpdateView(core.js:21879)
某事告诉我表单在订阅完成之前正在调用字段。有人建议修复吗?
*编辑添加的component.html
<div class="form">
<app-dynamic-form [fields]="regConfig" (submit)="submit($event)"></app-dynamic-form>
<div class="margin-top">
{{ form.value | json }}
</div>
</div>
编辑2: 经过进一步调试后,我认为此问题是动态表单组件正在尝试从服务返回项目配置之前构建表单。我该如何保护自己免受侵害?
答案 0 :(得分:0)
我终于通过在其动态表单标签中添加*ngIf
来使其工作。这样做是为了阻止动态表单尝试加载,直到它包含要处理的变量为止。
示例代码
<div class="form">
<app-dynamic-form [fields]="regConfig" *ngIf="regConfig !== undefined" (submit)="submit($event)"></app-dynamic-form>
</div>