[英]Angular 5 reactive form- updating formControl through the html does not update the value, only the control
I have a service with a FormGroup named mainForm- 我有一个名为mainForm-的FormGroup服务。
export class DepositFormDataService{
this.mainForm = this.formBuilder.group({
title: ['', Validators.required],
category: '',
type: '',
languages: this.formBuilder.array([]),
});
}
get title(): FormControl{
return this.mainForm.get('title') as FormControl;
}
}
In a component I use this service- 在组件中,我使用此服务-
constructor(public depositFormDataService: DepositFormDataService) {}
HTML: HTML:
<input matInput [formControl]="depositFormDataService.title">
When the user writes "b" for example I see in the debug a difference if I look on the FormGroup depositFormDataService.mainForm: 例如,当用户写“ b”时,如果在FormGroup depositFormDataService.mainForm上查找,我会在调试中看到不同:
in: Controls --> title --> value = b 在:控件->标题->值= b
in: value --> title --> null in:值->标题->空
Why? 为什么?
I found this post in git- https://github.com/angular/angular/issues/13792 我在git- https://github.com/angular/angular/issues/13792中找到了这篇文章
I tries to do this hack in the component- 我尝试在组件中进行此破解-
ngOnInit() {
this.onChanges();
}
onChanges(): void {
this.depositFormDataService.title.valueChanges
.pipe(takeUntil(this.titleDestroy))
.subscribe(value => {
this.depositFormDataService.mainForm.get('title').patchValue(value, {emitEvent: false});
}
But it did not work and the value was still "null". 但是它没有用,并且值仍然是“ null”。
Any idea how to make the value be sync with the value inside the controls? 任何想法如何使值与控件内的值同步?
It causes a strange problem that depositFormDataService.mainForm.status differs from the depositFormDataService.title.status. 这会导致一个奇怪的问题,即depositFormDataService.mainForm.status与depositFormDataService.title.status不同。
我认为在HTML中,您应该使用formControlName而不是formcontrol,如下所示:
<input formControlName="title" matInput >
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.