要求选中一个复选框 [英] Requiring a checkbox to be checked

查看:108
本文介绍了要求选中一个复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在使用FormBuilder for Angular选中复选框之前禁用按钮.我不想显式地检查复选框的值,而是希望使用验证器,以便我可以简单地检查form.valid.

I want a button to be disabled until a checkbox has been checked using a FormBuilder for Angular. I don't want to explicitly check the value of the checkbox and would prefer to use a validator so that I can simply check form.valid.

在两种验证情况下,复选框均为

In both validation cases below the checkbox is

interface ValidationResult {
  [key:string]:boolean;
}

export class CheckboxValidator {
  static checked(control:Control) {
    return { "checked": control.value };
  }
}

@Component({
  selector: 'my-form',
  directives: [FORM_DIRECTIVES],
  template: `  <form [ngFormModel]="form" (ngSubmit)="onSubmit(form.value)">
    <input type="checkbox" id="cb" ngControl="cb">
    <button type="submit" [disabled]="!form.valid">
    </form>`
})

export class SomeForm {
  regForm: ControlGroup;

  constructor(fb: FormBuilder) {
    this.form = fb.group({
      cb: [ CheckboxValidator.checked ]
      //cb: [ false, Validators.required ] <-- I have also tried this
    });
  }

  onSubmit(value: any) {
    console.log('Submitted: ', this.form);
  }
}

推荐答案

.ts

@Component({
  selector: 'my-app', 
  template: `
    <h1>LOGIN</h1>
    <form [ngFormModel]="loginForm"  #fm="ngForm"  (submit)="doLogin($event)"> 

          <input type="checkbox" id="cb" ngControl="cb" #cb="ngForm" required>
          <button type="submit" [disabled]="!loginForm.valid">Log in</button>

          <br/>
              <div>Valid ={{cb.valid}}</div>
              <div>Pristine ={{cb.pristine}}</div>
              <div>Touch ={{cb.touched}}</div>
              <div>form.valid?={{loginForm.valid}}</div>
          <BR/>
          <BR/>

    </form>
    `,
  directives: [ROUTER_DIRECTIVES,FORM_DIRECTIVES,CORE_DIRECTIVES]
})

export class Login { 
  constructor(fb: FormBuilder) {
    this.loginForm = fb.group({
      cb: [false, Validators.required],
    //cb: ['',Validators.required] - this will also work.

    });
  }
  doLogin(event) {
    console.log(this.loginForm);
    event.preventDefault();
  }
}

工作柱塞 >.

请让我知道是否需要任何更改.

Please let me know if any changes required.

这篇关于要求选中一个复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆