禁用不使用 formControlName 进入角度 2 中的模型驱动表单?

Sha*_*mor 7 angular

我正在使用模型驱动模板。如果未选中复选框,我想禁用输入。但它不适用于 formControlName。我尝试了三种方式。给这里

 1.disabled="!filterForm.value.customer_limit"
 2.[disabled]="!filterForm.value.customer_limit"
 3.[readonly]="!filterForm.value.customer_limit"
Run Code Online (Sandbox Code Playgroud)

这是我的 HTML 代码:

 <md-checkbox [checked]="filterForm.value.customer_limit" formControlName="customer_limit">
                        <md-input-container class="full-width">
                            <input mdInput
                                   formControlName="customer_limit_input"
                                   [disabled]="!filterForm.value.customer_limit"
                                   placeholder="Limit to customers">
    </md-input-container>
    </md-checkbox>
Run Code Online (Sandbox Code Playgroud)

有任何想法请帮助我。谢谢

AJT*_*T82 5

用反应式形式,[disabled]还是disabled不行。您可以使用的是检查复选框是否被选中并禁用或启用输入字段。

首先,我从复选框内删除了输入字段,不确定为什么它被放置在那里。

然后,在构建表单时,我做了一个 if 语句来检查输入字段的值customer_input,如果为 false,则禁用输入字段:

if this.myForm.get('customer_limit').value === true
  this.myForm.get('customer_limit_input').enable()
Run Code Online (Sandbox Code Playgroud)

如果您最初知道 的布尔值customer_limit,则可以跳过上述内容,只需最初禁用该字段(如果是这种情况),就像 Shailesh 所建议的那样:

customer_limit_input: [{value: 'something', disabled: true}]
Run Code Online (Sandbox Code Playgroud)

我放置了一个更改事件来观察复选框的状态,并在发生更改时调用一个函数:

<md-checkbox (change)="disableEnableInput(myForm.get('customer_limit').value)" 
  formControlName="customer_limit">
</md-checkbox>
<md-input-container class="full-width">
  <input mdInput formControlName="customer_limit_input">
</md-input-container>
Run Code Online (Sandbox Code Playgroud)

功能disableEnableInput()

disableEnableInput(bool: boolean) {
  if bool === true
    this.myForm.get('customer_limit_input').enable()
  else
    this.myForm.get('customer_limit_input').disable()
}
Run Code Online (Sandbox Code Playgroud)

我不知道是否有更优雅的解决方案(?)但这就是我迄今为止所使用的。

这是演示