【问题标题】:How to disable form control but keep value如何禁用表单控制但保持价值
【发布时间】:2017-06-30 01:25:57
【问题描述】:

我有一个反应形式。在编辑时,我希望禁用控件。

以下工作:

   this.myForm.controls['analysis_horizon'].disable();

但是,key analysis_horizo​​n 不再在我的 myForm.value 哈希中。

如何禁用具有反应式表单的字段但将值保留在表单值哈希中?

我试过 [disabled]= 但我得到以下信息:

It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true
      when you set up this control in your component class, the disabled attribute will actually be set in the DOM for
      you. We recommend using this approach to avoid 'changed after checked' errors.

      Example: 
      form = new FormGroup({
        first: new FormControl({value: 'Nancy', disabled: true}, Validators.required),
        last: new FormControl('Drew', Validators.required)
      });

我在编辑时将数据库中的数据加载到表单控件中,但我需要一个不允许更改的字段。

【问题讨论】:

  • 它告诉你直接在 HTML 中使用 disabled 属性,而不是与 formcontrol 一起使用。
  • 鉴于它没有改变,你可以自己把它放回价值,无论是什么消耗它,Object.assign 或其他东西。
  • 也许我理解错了,但是,为什么不按照消息建议的那样做:yourFormControl: new FormControl({value: yourPresetValue, disabled: true})
  • 我知道这已经过时了,但是响应式表单有另一种称为 form.getRawValue() 的方法可以为您执行此操作我不能说它在 100% 的时间内有效,但是当您使用任何 setValue 或 patch Value 方法

标签: angular


【解决方案1】:

我在尝试使用响应式表单实现 Angular Material Datepicker 时遇到了这个问题 - 我希望禁用输入,以便只有选择器可以设置日期,但是当您使用 disabled 属性时,Angular 会对您大喊大叫在模板中,然后在组件表单组代码中删除表单中的值。

我想出的解决方案是使用 CSS 来防止与输入的交互:

.disable-pointer-events {
   pointer-events: none;
}
<input
  class="disable-pointer-events"
  formControlName="yourControlName"
/>

【讨论】:

    【解决方案2】:

    尝试在方法禁用中添加onlySelf: true

    this.myForm.controls['analysis_horizon'].disable({onlySelf: true});
    

    【讨论】:

    • 欢迎瓦西尔!你能用代码标签附上你的代码吗?
    • 这没有得到预期的效果。它还禁用表单控制。
    【解决方案3】:

    我的解决方案是使用 [attr.disabled]:

    <select formControlName="foo"
      [attr.disabled]="disabled == true ? true : null"> 
    </select>
    

    假设您的组件中有一个 disabled 属性。 您必须返回 null 而不是 false 才能启用输入。

    【讨论】:

    • 尽管在这种情况下 Angular 没有发出警告,但它仍然使应用程序容易受到“检查后更改”错误的影响。
    【解决方案4】:

    如果您不想使用 getRawValue 来改变从表单中获取值的正常方式,这是另一种选择。我更喜欢 readonly 的更多原因:https://stackoverflow.com/a/7730719/1678151.

    我的解决方案还展示了如何填写表单控件。

    组件.ts

    fillForm(data: any){
     if (data != null && data.firstName){
       this.form.patchValue({
         firstName: data.firstName
       })    
       this.firstNameIsReadOnly = true;
     } 
    

    模板.html

    <input formControlName="firstName" [readonly]='firstNameIsReadOnly'>
    

    styles.scss

    input[readonly] {
     color: rgba(0,0,0,.38);
    }
    

    【讨论】:

      【解决方案5】:

      您可以使用 getRawValue() 代替 value 属性。根据documentation

      FormGroup 的聚合值,包括所有禁用的控件。

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

      this.myForm.getRawValue()
      

      【讨论】:

      • 惊人的嘘声
      • 你救了我的命?
      猜你喜欢
      • 2020-01-02
      • 1970-01-01
      • 1970-01-01
      • 2022-06-15
      • 1970-01-01
      • 1970-01-01
      • 2019-06-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多