angular – 要求选中复选框

前端之家收集整理的这篇文章主要介绍了angular – 要求选中复选框前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想要一个按钮被禁用,直到使用FormBuilder for Angular检查复选框。我不想显式检查复选框的值,而是希望使用验证器,以便我可以简单地检查form.valid。

在下面的两个验证案例中,复选框都是

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

Working Plunker

如果需要更改,请告诉我。

原文链接:https://www.f2er.com/angularjs/143891.html

猜你在找的Angularjs相关文章