我在ngOnInit()中使用了formgroup代码,并且我在ngOnInit()中使用了服务。由于异步表单不起作用。下面的完整代码stackblitz url工作时我在构造函数中使用dymmy json。 working-form-dymmyjson CODE URL
我得到了服务的回复。我在ngOnInit()中使用了服务。由于异步调用表单不起作用,下面是我的代码url与服务。 notworking-form-using service stackblitz url
以下是服务代码 this.dataService.getData()。then(data => this.users = data);我在服务中尝试过formgroup代码,但是遇到了错误。 我在控制台附加截图中得到了回复。
下面是我的构造函数代码:
constructor(private dataService: DataService,private fb: FormBuilder) {
this.myForm = this.fb.group({
users: this.fb.array([])
})
this.users =[{"name":"manu","displayOrder":1,"data":[{"category":"electrical","name":"ele"}]},{"name":"divya","displayOrder":1,"data":[{"category":"tech","name":"ea_tcv"}]}];
this.test = [{"name":"manu","displayOrder":1,"data":[{"category":"electrical","name":"ele"}]},{"name":"divya","displayOrder":1,"data":[{"category":"tech","name":"ea_tcv"}]}];
}
下面是我的ngOnInit()代码,它具有服务和表单初始化。
ngOnInit() {
console.log("ramu");
this.dataService.getData().then(data => console.log(data));
this.dataService.getData().then(data => this.users=data);
this.dataService.getData().then(data => this.test=data);
let dataArr = new FormArray([]);
dataArr.push(new FormGroup({
'name': new FormControl(this.users[0].data[0].name),
'category': new FormControl(this.users[0].data[0].category)
}));
let formArr = <FormArray>this.myForm.controls.users;
formArr.push(this.fb.group({
name: this.users[0].name,
displayOrder: this.users[0].displayOrder,
data: dataArr
}));
}
答案 0 :(得分:1)
只需在回调then
中调用一个方法(或填充表单),就可以在值完成后填充表单:
this.dataService.getData().then(data => {this.users = data; this.patch()});
和方法:
patch() {
let dataArr = new FormArray([]);
dataArr.push(new FormGroup({
'name': new FormControl(this.users[0].data[0].name),
'category': new FormControl(this.users[0].data[0].category)
}));
let formArr = <FormArray>this.myForm.controls.users;
formArr.push(this.fb.group({
name: this.users[0].name,
displayOrder: this.users[0].displayOrder,
data: dataArr
}));
}
您的分叉 StackBlitz