Search code examples
angulartwitter-bootstraptypescriptangular-formsangular-validation

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


I have a register form with a checkbox for the T of S. The 'Register' button (the form) gets enabled when the form is valid, and disabled when invalid. I can fill out the form and select the checkbox and the register button becomes enabled/clickable. So the form is valid, but when I uncheck it, the register button remains enabled/clickable and the form remains valid. It doesn't become invalid!

FYI - I added a couple of statements into the input 'name' and '[checked]' to see if that would get it to work but had no luck.

Here is my form and some of the .ts code. Some code is left out to keep it short.

@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>


Solution

  • Ah, didn't see it before:

    You need to use Validators.requiredTrue in order for the checkbox control to work properly.