Angular disable 导致无法获取值的解决办法

最近再使用 Angular 写后台的时候,出现 FormControl Disable() 无法获取值,下面是示例代码:

从后端获取值:

getCloudEmailSubscribeInfo() {
    this.loading = true;
    this.sub = this.phoneNumber.getEmailSubscribeInfo(this.data.id).subscribe(res => {
        this.emailFormControl.setValue(res.email);
        this.emailFormControl.disable();
        this.confirmFormControl.setValue(res.confirmed ? 1 : 0);
    }, error => {
        this.snackBar.open(error.error.message ?? error.message, '关 闭', {
            horizontalPosition: 'start',
            verticalPosition: 'bottom',
        });
    }, () => {
        this.loading = false;
    });
}

更改之后保存,但是出现错误:

onConfirmEmailEdit($event): void {
    if (!this.validateForm(this.emailSubscribeFormGroup)) {
        return;
    }
    this.saveCloudLoading = true;
    this.sub = this.phoneNumber.saveEmailSubscribeInfo(this.data.id, this.emailFormControl.value(),
        this.confirmFormControl.value()).subscribe(res => {
        if (res.returnResult === 'ok') {
            this.dialogRef.close();
        }
    }, error => {
        this.snackBar.open(error.error.message ?? error.message, '关 闭', {
            horizontalPosition: 'start',
            verticalPosition: 'bottom',
        });
    });
}

出错内容如下:

ERROR TypeError: this.emailFormControl.value is not a function

具体截图如下:

ERROR TypeError: this.emailFormControl.value is not a function

出现问题的原因

FormControl Disable() 状态无法获取值。

解决方案

出现 FormControl Disable() 无法获取值您可以使用 getRawValue() 而不是 value 属性。文档解释如下:

FormGroup 的聚合值,包括任何禁用的控件。

如果您想包含所有值而不考虑禁用状态,请使用此方法。否则,value 属性是获取组值的最佳方式。

我们可疑使用如下写法:

this.myForm.getRawValue()

参考资料