【问题标题】:Angular disable input if checkbox is checked如果选中复选框,则角度禁用输入
【发布时间】:2021-03-09 16:32:24
【问题描述】:

我有一个输入和一个复选框,如果选中复选框,我想禁用输入。有什么建议吗?

<input formControlName="checkbox" type="checkbox">
<input formControlName="input" type="number">

【问题讨论】:

标签: angular angular-reactive-forms angular-forms


【解决方案1】:

您可以在复选框控件上使用可观察的反应形式 valueChanges 来实现此目的。

@Component({...})
export class MyComponent implements OnInit {
   // Your form
   form:FormGroup = this.fb.group({checkbox: false, input: ''});
   
   constructor(private fb:FormBuilder){}

   ngOnInit() {
      // Subscribe to value changes - this will trigger whenever the value of your checkbox is changed (through click, or programmatically)
      this.form.get('checkbox').valueChanges
         .subscribe(value => {
            if (value) {
               // disable the input when new value is true
               this.form.get('input').disable();
            } else {
               // (re-)enable the input when new value is false
               this.form.get('input').enable();
            }
         })
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-26
    • 1970-01-01
    • 2014-07-11
    • 2022-01-19
    • 1970-01-01
    • 2021-02-22
    • 2013-12-24
    • 2020-06-22
    相关资源
    最近更新 更多