I'm having an issue with the Angular Material Checkbox which I thought would be a relatively simple thing, but for some reason I can't get it to work.
I have a div which I only want to show when the mat-checkbox is checked, but it doesn't seem to want to work with *ngIf even though I found an example of it working here: https://stackblitz.com/edit/angular-mat-checked?file=app%2Fcheckbox-overview-example.html
I tried applying very similar code to my project, but it doesn't seem to want to work, nor does anything else I've tried.
<mat-checkbox [(ngModel)]="checked" [checked]="false">
I agree to {{clientName}} storing my details.
<a href="#" target="_blank">View full terms & conditions</a>
</mat-checkbox>
<div *ngIf="checked" id="contactOptionsGroup">
<p>Stay updated with news, features, and offers related to {{clientName}}.</p>
<mat-checkbox>Phone</mat-checkbox>
<mat-checkbox>Email</mat-checkbox>
</div>
It seems like being able to show and hide this div by checking and unchecking should be relatively simple but I appear to be stumped. I might be missing something completely obvious, but I can't see what it may be.
There will be another instance of this functionality later on in the project too, so they'll need to work independently of each other.
If anyone has help or suggestions, I'd be eternally grateful.
Angular Material can be checked dynamically using checked property of <mat-checkbox> element. Checkbox can also be checked using Angular ngModel . The ngModel can be used for two-way binding.
Click action config When user clicks on the mat-checkbox , the default behavior is toggle checked value and set indeterminate to false . This behavior can be customized by providing a new value of MAT_CHECKBOX_DEFAULT_OPTIONS to the checkbox.
To set mat-checkbox checked by default we use checked attribute or [ngModel] as shown below. We can set the IsChecked property to true in constructor.
mat-checkbox ouput html mat-checkbox will generate a span element with the class . mat-checkbox-background through which we can control the background color of checkbox. Now all we have to do is adding background-color css to the . mat-checkbox-background class.
You don't need to define a variable in component. You could also reference the checkbox
<mat-checkbox #termsAndConditions>
I agree to {{clientName}} storing my details.
<a href="#" target="_blank">View full terms & conditions</a>
</mat-checkbox>
<div *ngIf="termsAndConditions.checked" id="contactOptionsGroup">
<p>Stay updated with news, features, and offers related to {{clientName}}.</p>
<mat-checkbox>Phone</mat-checkbox>
<mat-checkbox>Email</mat-checkbox>
</div>
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