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

use*_*496 3 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>
Run Code Online (Sandbox Code Playgroud)

Sid*_*era 5

我认为拥有一个带有所需验证器的响应式表单将使您更好地控制表单实现。

你可以创建一个看起来像这样的响应式表单:

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) {}
}
Run Code Online (Sandbox Code Playgroud)

然后您可以使用[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>
Run Code Online (Sandbox Code Playgroud)

这是供您参考的示例工作演示


Har*_*mpi 3

使用[disabled]带有一个标志的属性。

组件.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>
Run Code Online (Sandbox Code Playgroud)

组件.ts

isDisabled: boolean = false;
Run Code Online (Sandbox Code Playgroud)

这将解决你的问题..