Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

disabled button if checkbox is unchecked

Tags:

html

angular

I have an Angular component with a checkbox and a button that should be disabled if the checkbox is unchecked. What is the correct way for this?

<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>
like image 365
user2004 Avatar asked Jan 25 '23 12:01

user2004


1 Answers

I think having a Reactive Form in place with required validators would give you more control over the form implementation.

You could create a Reactive Form that looks something like this:

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) {}
}

And then you could use the [disabled] property binding syntax and bind it to form.invalid property to disable the button when the form is 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>

Here's a Sample Working Demo for your ref.

like image 87
SiddAjmera Avatar answered Jan 28 '23 10:01

SiddAjmera