【问题标题】:How to get values from disabled form controls in a form group?如何从表单组中的禁用表单控件中获取值?
【发布时间】:2021-08-09 23:00:38
【问题描述】:

我尝试使用表单状态对象初始化我的新 FormControl,然后我注意到这个控件不会影响我的表单验证,并且它也会从 FormGroup 值中消失。

this.userForm = new FormGroup({
  email: new FormControl('', Validators.required),
  firstName: new FormControl('',Validators.required),
  lastName: new FormControl('',Validators.required),
  role: new FormControl({value: 'MyValues', disabled: true},Validators.required),
 })

现在如果我尝试这样做:

this.userForm.value //email, firstName, lastName

有人遇到过这个问题吗?有什么解决办法吗? 角度版本:5.2.6

【问题讨论】:

  • 我不确定我是否理解。对我来说似乎很好。当我写this.userForm = new FormGroup({ email: new FormControl('test', Validators.required), firstName: new FormControl('', Validators.required), lastName: new FormControl('', Validators.required), role: new FormControl({value: 'MyValues', disabled: true}, Validators.required), }) console.log(this.userForm.value); 时,我看到了我的价值观。
  • @AlexandreAnnic 是的,你理解得很好。但这不起作用,我还注意到禁用的控件由于其状态(已禁用)而不能有效或无效
  • 禁用的控件不会按值返回,也不会在表单验证时被考虑。如果要打印角色值,请使用userForm.getRawValue()
  • @Jota.Toledo 谢谢。它对我有用。
  • 添加了一个答案,因为这可能对其他人有用

标签: angular forms angular-reactive-forms


【解决方案1】:

这不是问题,是预期的行为。如果您想包含所有值而不考虑禁用状态,请使用以下命令:

this.userForm.getRawValue()

【讨论】:

    【解决方案2】:

    感谢 @jota-toledo 为我提供了 80% 的所需。

    对于那些正在寻找相同问题的解决方案但对于嵌套表单的人来说,我可以通过改变我的习惯来解决

    this.userForm.get('nestedForm').value
    

    this.userForm.getRawValue().nestedForm
    

    【讨论】:

      【解决方案3】:

      如果有人正在寻找解决方案以在 FormGroup 中获得禁用的 FormArrayFormControl

      试试这个 - (this.formName.controls['formArrayName'] as FormGroup).getRawValue();

      【讨论】:

        【解决方案4】:

        TS解决方案:

        this.userForm.getRawValue()
        

        仅 HTML 解决方案:

        <input formControlName="name" [readonly]="condition">
        

        仅 CSS 解决方案:

        pointer-events: none;
        

        Html 和 Css 解决方案将阻止用户与输入进行交互,但响应式表单将获得价值

        【讨论】:

          猜你喜欢
          • 2018-09-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-09-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-05-23
          相关资源
          最近更新 更多