If you're looking to add a red border using custom CSS, here's an example of how it can be done:
.mat-mdc-radio-group.ng-touched.ng-invalid {
.mdc-radio__outer-circle {
border-color: red !important;
}
.mdc-label {
color: red;
}
}
.mat-mdc-checkbox.ng-touched.ng-invalid {
.mdc-checkbox__background {
border-color: red !important;
}
.mdc-label {
color: red !important;
}
}
Keep in mind that adding a mandatory checkbox validation with a red border might not be the best user experience unless necessary. The code provided focuses on styling radio groups easily without using mat form field.
For the full implementation, refer to the HTML and TypeScript codes below:
HTML Code:
<form [formGroup]="form" (ngSubmit)="form.markAllAsTouched();">
<mat-label>Enter your Selection</mat-label>
<br />
<mat-radio-group aria-label="Select an option" formControlName="radios">
@for (item of radioValues; track item){
<mat-radio-button [value]="item.id">{{item.label}}</mat-radio-button>
}
</mat-radio-group>
<br />
@if(form.get('radios'); as radio) { @if (radio?.touched &&
radio?.errors?.required) {
<mat-error>Selection is required</mat-error>
} }
<hr />
<mat-label>Enter your Checkboxes</mat-label>
@for (item of checkboxValues; track item){
<mat-checkbox [value]="item.key" [formControlName]="item.value">
{{item.value}}
</mat-checkbox>
}
<hr />
<br />
<button type="submit">submit</button>
</form>
TypeScript Code:
import { Component } from '@angular/core';
import {
FormControl,
FormGroup,
ReactiveFormsModule,
Validators,
} from '@angular/forms';
import { MatRadioModule } from '@angular/material/radio';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatFormFieldModule } from '@angular/material/form-field';
import { CommonModule } from '@common';
/**
* @title Basic radios
*/
@Component({
selector: 'radio-overview-example',
templateUrl: 'radio-overview-example.html',
styleUrl: 'radio-overview-example.css',
standalone: true,
imports: [
MatRadioModule,
ReactiveFormsModule,
MatCheckboxModule,
CommonModule,
MatFormFieldModule,
],
})
export class RadioOverviewExample {
radioValues = [
{ id: 1, label: 'apple' },
{ id: 2, label: 'banana' },
];
checkboxValues = [
{ key: 'apple', value: 'apple', selected: false },
{ key: 'banana', value: 'banana', selected: false },
{ key: 'orange', value: 'orange', selected: false },
};
form = new FormGroup({
radios: new FormControl(null, Validators.required),
});
ngOnInit() {
this.checkboxValues.forEach((item: any) => {
this.form.addControl(
item.value,
new FormControl(null, Validators.required)
);
});
// this.form.get('radios')!.markAsTouched();
// this.form.get('radios')!.markAsDirty();
}
}
To see the errors, simply click on the submit button!