【发布时间】:2019-04-06 18:51:49
【问题描述】:
以下是我的一段代码,为了简洁起见,我已经简化了代码。
ngOnInit() {
//intialize form fields
this.form = this.builder.group({
name: '',
age: '',
location: '',
});
//Call to the service
this.dataService.getDetails().subscribe(
(data) => {
this.dataArray = data;
if (this.dataArray[this.count].status === 'OK') {
let docs = {};
this.someService.getDocs(this.dataArray[this.count].id).subscribe(
(data) => {
docs = data;
console.log("docs: ", docs);
this.setFormValues(docs);//set form values
},
(err) => {
console.log(err);
console.log('Something happened');
}
);
}
},
(err) => {
console.log(err);
console.log('Something happened',err);
}
);
}
现在在setFormValues() 中,我已经打印了字段的值,并且到目前为止它工作正常,但是接下来当我尝试使用setValue 或patchValue 将值绑定到form 时,它根本不会用从service 获取的值更新form。
这方面的更多代码
public setFormValues(doc: DocsDTO) {
if (doc!= null) {
console.log("setFormValues", doc);
this.form.patchValue({
name: doc.name == null ? '' : doc.name.text,
age: doc.age == null ? '' : doc.age.text,
location: doc.location == null ? '' : doc.location.text,
})
}
}
这是我的form 的样子
<form [formGroup]="form">
<mat-card-content>
<input placeholder="name" [formControl]="name" id="name"
ngDefaultControl></input>
<input placeholder="age" [formControl]="age" id="age" ngDefaultControl></input>
</mat-card-content>
</mat-card>
</form>
注意:当我不使用FormBuilder 并使用FormControl 初始化表单字段并使用this.name.setValue() 设置表单值时,它可以正常工作。
我对 angular 很陌生,我不确定我在这里做错了什么。
【问题讨论】:
-
您的代码 ts 代码是正确的,您是否在控制台中遇到任何错误?我假设,您的 JSON 数据可能存在问题。
-
没有错误。我也尝试过硬编码这些值。
-
我已经根据您的场景在 stackblitz 上创建了一个示例应用程序,它运行良好,请查看此链接 stackblitz.com/edit/… 并告诉我
-
我认为问题在于您将 html 与 formcontrol 绑定并在 formgroup 中设置了一个值,这就是您没有在控件中获取值的原因。请检查 stackblitz 示例 html 代码。
标签: angular typescript angular6 angular-reactive-forms