繁体   English   中英

Angular 5反应性表单-通过html更新formControl不会更新值,只有控件

[英]Angular 5 reactive form- updating formControl through the html does not update the value, only the control

我有一个名为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;
    }
}

在组件中,我使用此服务-

 constructor(public depositFormDataService: DepositFormDataService) {}

HTML:

 <input matInput [formControl]="depositFormDataService.title">

例如,当用户写“ b”时,如果在FormGroup depositFormDataService.mainForm上查找,我会在调试中看到不同:

在:控件->标题->值= b

in:值->标题->空

为什么?

我在git- https://github.com/angular/angular/issues/13792中找到了这篇文章

我尝试在组件中进行此破解-

ngOnInit() {
    this.onChanges();
}

onChanges(): void {
    this.depositFormDataService.title.valueChanges
        .pipe(takeUntil(this.titleDestroy))
        .subscribe(value => {
            this.depositFormDataService.mainForm.get('title').patchValue(value, {emitEvent: false});
}

但是它没有用,并且值仍然是“ null”。

任何想法如何使值与控件内的值同步?

这会导致一个奇怪的问题,即depositFormDataService.mainForm.status与depositFormDataService.title.status不同。

我认为在HTML中,您应该使用formControlName而不是formcontrol,如下所示:

<input  formControlName="title" matInput >

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM