Angular 6:创建动态反应表单,但出现错误:“No No No modHFGen.dll;formGroup需要一个formGroup实例。请把一个递给我;
我目前正在创作一款带有角度6的反应式手风琴。我也在使用primeNG的手风琴模块 基于对象(cuList),将动态创建FormControl(输入框)。我创建了一个FormGroup,并使用FormBuilder动态添加了组。但是,我在运行时遇到了以下错误: (如果链接不起作用,请参阅下面的错误消息) 组件tsAngular 6:创建动态反应表单,但出现错误:“No No No modHFGen.dll;formGroup需要一个formGroup实例。请把一个递给我;,angular,typescript,angular6,angular-reactive-forms,Angular,Typescript,Angular6,Angular Reactive Forms,我目前正在创作一款带有角度6的反应式手风琴。我也在使用primeNG的手风琴模块 基于对象(cuList),将动态创建FormControl(输入框)。我创建了一个FormGroup,并使用FormBuilder动态添加了组。但是,我在运行时遇到了以下错误: (如果链接不起作用,请参阅下面的错误消息) 组件ts export class EmployerCuListComponent implements OnInit { @ViewChild('accordion') accordio
export class EmployerCuListComponent implements OnInit {
@ViewChild('accordion') accordion: Accordion;
reportForm: FormGroup; // form
cuList: EmployerCu[];
constructor(private _fb: FormBuilder) {
}
ngOnInit() {
this._employercuService.getEmployerCu().subscribe(data => {
this.cuList = data;
});
if (this.cuList) {
this.createForm(this.cuList);
}
}
createForm(cuList: EmployerCu[]) {
const group = {};
cuList.forEach((cu, index) => {
group['wages_' + index] = ['', [Validators.required]];
group['subkPay_' + index] = ['', [Validators.required]];
group['exsPay_' + index] = ['', [Validators.required]];
});
this.reportForm = this._fb.group(group); // create form with FormBuilder
}
}
我想这是一个时间问题?以及在对象初始化之前加载的页面
请帮忙!提前谢谢 我认为这是一个时间问题,我想我知道解决方法。。 更改: 为此:
ngOnInit() {
this._employercuService.getEmployerCu().subscribe(data => {
this.cuList = data;
if (this.cuList) {
this.createForm(this.cuList);
}
});
}
我相信如果没有这个更改,if语句总是在this.cuList设置之前命中,因此永远不会调用this.createForm
这是由于.subscribe()方法的异步性质造成的
仅供参考:
您可以验证这一点,但要
调试器
如果您这样做,您应该能够在浏览器的开发控制台中单步执行代码。上面的答案非常好,应该可以解决问题。为什么不调用此内部构造函数而不是ngOnInit@VithuBati,在构造函数中执行此类操作是不好的。组件构造函数应该只处理创建类,而在初始化组件后应该处理检索数据之类的事情,即
OnInit
非常好。这解决了我的问题。是的,这是subscribe方法的异步特性。谢谢你带来这个。
export class EmployerCuListComponent implements OnInit {
@ViewChild('accordion') accordion: Accordion;
reportForm: FormGroup; // form
cuList: EmployerCu[];
constructor(private _fb: FormBuilder) {
}
ngOnInit() {
this._employercuService.getEmployerCu().subscribe(data => {
this.cuList = data;
});
if (this.cuList) {
this.createForm(this.cuList);
}
}
createForm(cuList: EmployerCu[]) {
const group = {};
cuList.forEach((cu, index) => {
group['wages_' + index] = ['', [Validators.required]];
group['subkPay_' + index] = ['', [Validators.required]];
group['exsPay_' + index] = ['', [Validators.required]];
});
this.reportForm = this._fb.group(group); // create form with FormBuilder
}
}
ngOnInit() {
this._employercuService.getEmployerCu().subscribe(data => {
this.cuList = data;
});
if (this.cuList) {
this.createForm(this.cuList);
}
}
ngOnInit() {
this._employercuService.getEmployerCu().subscribe(data => {
this.cuList = data;
if (this.cuList) {
this.createForm(this.cuList);
}
});
}