Angular 7 表单和 Bootstrap 复选框在选中时验证表单,但在未选中时不会失效

Angular 7 form and Bootstrap checkbox validates form when checked but doesn't invalidate when unchecked

我有一个注册表单,上面有一个 T 或 S 的复选框。'Register' 按钮(表单)在表单有效时启用,在无效时禁用。我可以填写表格,select 复选框和注册按钮变为 enabled/clickable。所以表格是有效的,但是当我取消选中它时,注册按钮仍然是 enabled/clickable 并且表格仍然有效。它不会失效!

仅供参考 - 我在输入 'name' 和“[checked]”中添加了一些语句,看看是否可以正常工作,但没有成功。

这是我的表格和一些 .ts 代码。为了简短起见,省略了一些代码。

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit, AfterViewInit {
  // some variables here removed
  registerForm: FormGroup;
  bsConfig: Partial<BsDatepickerConfig>;
  terms = false;
  
  

  constructor(private authService: AuthService, private router: Router,
              private alertService: AlertService, private fb: FormBuilder, private zone: NgZone) {}

  ngOnInit() {
    this.bsConfig = {
      containerClass: 'theme-red'
    };
    this.createRegisterForm();
  }
  
  createRegisterForm() {
    this.registerForm = this.fb.group({
      terms: ['', Validators.required],
    });
  }
<form [formGroup]="registerForm" (ngSubmit)="register()">
  <div class="form-group">
    <div class="form-check">
      <input class="form-check-input" id="gridCheck" 
         [ngClass]="{'is-invalid': registerForm.get('terms').errors && registerForm.get('terms').touched}" 
         name="terms" 
         type="checkbox"  
         formControlName="terms">
      <label class="form-check-label" for="gridCheck">Agree to terms</label>
    </div>
  </div>

  <div class="form-group text-center">
    <button class="btn btn-yb w-100" [disabled]="!registerForm.valid" type="submit">
        <span *ngIf="loadingRegister" class="spinner-border spinner-border-sm color-yb-white" role="status" aria-hidden="true"></span>
        <span class="sr-only">Loading...</span>
        <span *ngIf="!loadingRegister">Register</span>
    </button>
  </div>
</form>

啊,之前没看到:

您需要使用 Validators.requiredTrue 才能使复选框控件正常工作。