【问题标题】:How to check multiple checkboxes programmatically in a formGroup on reactive form?如何在反应形式的formGroup中以编程方式检查多个复选框?
【发布时间】:2017-07-19 19:40:18
【问题描述】:

我正在使用 Angular2 RC 5,并尝试实现响应式表单(模型驱动)

我这样定义复选框

usageRights : new FormGroup({
     all_usage   : new FormControl( '' ),
     digital     : new FormControl( '' ),
     outdoor     : new FormControl( '' ),
     print       : new FormControl( '' ),
     radio       : new FormControl( '' ),
     tv          : new FormControl( '' )
})

有一个按钮,当它被点击时,我喜欢检查组中的所有复选框。我当前的实现是在单击按钮时使用一个函数,但我不知道如何在我的 ts 文件中检查这些复选框

我的 checkAll 函数

checkAll( control, e ) {
    e.preventDefault();
    console.log(control);
}

control 是包含所有复选框的 formGroup(usageRights),它记录正​​常。我相信我可以将变量与[checked] 结合使用,然后在单击按钮时更新变量,但我觉得这不是正确的做法。

请告诉我这应该怎么做。我被困住了。

【问题讨论】:

    标签: javascript angular typescript checkbox


    【解决方案1】:

    我想通了

    checkAll( control, e ) {
        e.preventDefault();
    
        for( let key in control.controls ) {
            control.controls[ key ].setValue( true );
        }
    }
    

    setValue 函数是 formControl 原型 更多文档在这里https://angular.io/docs/ts/latest/api/forms/index/FormControl-class.html

    当其他人陷入同一件事时,将其留在这里

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-13
      • 2012-10-01
      • 2019-07-16
      • 2020-01-09
      • 1970-01-01
      • 2017-12-29
      • 2021-06-07
      相关资源
      最近更新 更多