加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 要求选中复选框

发布时间:2020-12-17 08:01:44 所属栏目:安全 来源:网络整理
导读:我想要一个按钮被禁用,直到使用FormBuilder for Angular检查复选框。我不想显式检查复选框的值,而是希望使用验证器,以便我可以简单地检查form.valid。 在下面的两个验证案例中,复选框都是 interface ValidationResult { [key:string]:boolean;}export cl
我想要一个按钮被禁用,直到使用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。

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读