angular – 要求选中复选框

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

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

  1. interface ValidationResult {
  2. [key:string]:boolean;
  3. }
  4.  
  5. export class CheckBoxValidator {
  6. static checked(control:Control) {
  7. return { "checked": control.value };
  8. }
  9. }
  10.  
  11. @Component({
  12. selector: 'my-form',directives: [FORM_DIRECTIVES],template: ` <form [ngFormModel]="form" (ngSubmit)="onSubmit(form.value)">
  13. <input type="checkBox" id="cb" ngControl="cb">
  14. <button type="submit" [disabled]="!form.valid">
  15. </form>`
  16. })
  17.  
  18. export class SomeForm {
  19. regForm: ControlGroup;
  20.  
  21. constructor(fb: FormBuilder) {
  22. this.form = fb.group({
  23. cb: [ CheckBoxValidator.checked ]
  24. //cb: [ false,Validators.required ] <-- I have also tried this
  25. });
  26. }
  27.  
  28. onSubmit(value: any) {
  29. console.log('Submitted: ',this.form);
  30. }
  31. }
.TS
  1. @Component({
  2. selector: 'my-app',template: `
  3. <h1>LOGIN</h1>
  4. <form [ngFormModel]="loginForm" #fm="ngForm" (submit)="doLogin($event)">
  5.  
  6. <input type="checkBox" id="cb" ngControl="cb" #cb="ngForm" required>
  7. <button type="submit" [disabled]="!loginForm.valid">Log in</button>
  8.  
  9. <br/>
  10. <div>Valid ={{cb.valid}}</div>
  11. <div>Pristine ={{cb.pristine}}</div>
  12. <div>Touch ={{cb.touched}}</div>
  13. <div>form.valid?={{loginForm.valid}}</div>
  14. <BR/>
  15. <BR/>
  16.  
  17. </form>
  18. `,directives: [ROUTER_DIRECTIVES,FORM_DIRECTIVES,CORE_DIRECTIVES]
  19. })
  20.  
  21. export class Login {
  22. constructor(fb: FormBuilder) {
  23. this.loginForm = fb.group({
  24. cb: [false,Validators.required],//cb: ['',Validators.required] - this will also work.
  25.  
  26. });
  27. }
  28. doLogin(event) {
  29. console.log(this.loginForm);
  30. event.preventDefault();
  31. }
  32. }

Working Plunker

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

猜你在找的Angularjs相关文章