如果未选中复选框,则禁用按钮

时间:2019-12-19 12:22:54

标签: html angular

我有一个带有复选框的Angular组件,如果未选中该复选框,则应禁用一个按钮。 正确的方法是什么?

<div class="form-check my-5">
  <input type="checkbox" class="form-check-input id="agreements">
  <label class="form-check-label" for="agreements">I have signed the agreements</label>
</div>

<button type="button" class="btn btn-outline-danger">Continue</button>

5 个答案:

答案 0 :(得分:4)

我认为拥有一个带有所需验证程序的反应式表单将使您对表单的实现有更多的控制。

您可以创建一个如下所示的反应式表单:

import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  form: FormGroup = this.fb.group({
    agreement: [null, Validators.required]
  });

  constructor(private fb: FormBuilder) {}
}

然后,您可以使用[disabled]属性绑定语法并将其绑定到form.invalid属性,以在表单无效时禁用按钮:

<form [formGroup]="form">
  <div class="form-check my-5">
    <input 
      type="checkbox" 
      class="form-check-input" 
      id="agreements">
    <label 
      class="form-check-label" 
      for="agreements">
      I have signed the agreements
    </label>
  </div>

  <button 
    type="button" 
    class="btn btn-outline-danger"
    [disabled]="form.invalid">
    Continue
  </button>
</form>

  

这是您推荐的Sample Working Demo

答案 1 :(得分:1)

[disabled]属性与一个标志一起使用。

component.html

<div class="form-check my-5">
  <input type="checkbox" class="form-check-input" [(ngModel)]="isDisabled" id="remember-me" name="rememberMe">
  <label class="form-check-label"  for="remember-me">I have signed the agreements</label>
</div>

<button type="button" [disabled]="!isDisabled" class="btn btn-outline-danger">Continue</button>

component.ts

isDisabled: boolean = false;

这将解决您的问题。

答案 2 :(得分:1)

使用ng-disabled属性:

<!DOCTYPE html>  
    <html ng-app>  
      
        <head>  
            <script src="http://code.angularjs.org/1.2.0/angular.min.js"></script>  
        </head>  
      
        <body>      <input type="checkbox" class="form-check-input id="agreements" ng-model="checked">
  <label class="form-check-label" for="agreements">I have signed the agreements</label>
</div>

<button type="button" class="btn btn-outline-danger" ng-model="button" ng-disabled="checked">Continue</button> </body>  
      
    </html>
    
    

答案 3 :(得分:1)

这是一个示例工作演示 https://stackblitz.com/edit/angular-fz73re

答案 4 :(得分:0)

您可以使用[disabled]属性来启用/禁用“提交”按钮:

  

TS文件:

export class AppComponent  {
  isDisabled: boolean = true;
  updateStatus($event){
   $event.target.checked === true ?  this.isDisabled = false: this.isDisabled = true;
  }
}
  

HTML文件

<div>
  <input type="checkbox"  id="remember-me"(change)="updateStatus($event)">
  <label for="remember-me" >I have signed the agreements</label>
</div>
<button  [disabled]="isDisabled" type="button">Continue</button>