【问题标题】:angular2 will not disable input based on true or false conditionangular2 不会根据真假条件禁用输入
【发布时间】:2017-01-12 12:16:42
【问题描述】:

我有一个基于以下内容的输入框:

如果更改收音机,我看到该值更改为 true 为 false:

<pre> {{model_parameters_general.estimationmethod=='ew'}} </pre>

那么哇为什么输入框会根据真为假禁用呢?

<input [disabled]="model_parameters_general.estimationmethod=='ew'" [(ngModel)]="model_parameters_general.lambda" 
                           formControlName="lambda" type="text" class="form-control">

编辑:

在日志中我得到了这个:

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)
  });

所以我在 rc6 中使用了响应式。

我将初始禁用设置为以下:

this.myForm = fb.group({
                lambda: new FormControl({value: .99, disabled: true}, Validators.required),

        }) 

那么我是否应该根据无线电输入的切换来启用?

【问题讨论】:

  • 如果你使用标签形式,你也应该为你的输入添加属性名称

标签: angular


【解决方案1】:

尝试使用 attr.disabled,而不是禁用

&lt;input [attr.disabled]="disabled?'':null"/&gt;

StackOverflow Answer

【讨论】:

    【解决方案2】:

    对于布尔属性,您需要将它们设置为 null 才能将它们删除

    <input [disabled]="model_parameters_general.estimationmethod=='ew' ? true : null" [(ngModel)]="model_parameters_general.lambda" 
      formControlName="lambda" type="text" class="form-control">
    

    【讨论】:

    • 我不明白你问题的最后一句话。也许缺少“如何”或其他什么?
    • html [disable] 的形式不起作用。默认情况下它始终启用。我可以禁用的唯一方法是在 formControl 中禁用。现在我需要监控我猜是 this.myForm.valueChanges subscribe 的事件
    • 监控事件的目的是什么?
    • 因为在反应形式中,我无法根据我的问题中发布的来自 angular2 的日志消息禁用或启用输入字段
    【解决方案3】:

    似乎在 rc.6 中,他们删除了在使用响应式表单时在模板绑定上动态禁用输入的功能。您必须监控更改并在您希望立即禁用的formControl 上致电.disable()。我更喜欢旧的做事方式,并希望他们能把它带回来或同样有用的解决方案。

    请加入related github issue

    【讨论】:

      【解决方案4】:

      试试下面的代码。

      setControl(name: any, Isenable: boolean): void {
          let ctrl = this.checkInForm.controls[name];
          console.log(ctrl);
          Isenable ? ctrl.enable() : ctrl.disable();
      }
      

      调用语句

      this.setControl('ctrl name', true);    // enbale it
        this.setControl('ctrl name', false);    // disable it
      

      谢谢 快乐编码!

      【讨论】:

        猜你喜欢
        • 2019-01-13
        • 2020-09-04
        • 2014-12-17
        • 2021-12-21
        • 1970-01-01
        • 2018-02-16
        • 1970-01-01
        • 2021-04-06
        • 2014-08-12
        相关资源
        最近更新 更多