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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With