I have an angular radio group with two radio buttons. None of them are selected initially. In that case, I want the label for the group to be red. When one of them is checked, remove red.
.html
<div>
<label for="odr" [ngClass]="{'invalid': myForm.get('odr').invalid}">Our Dear Relative: </label>
</div>
<div>
<mat-radio-group [formControl]="odr" value={{odr.value}}>
<mat-radio-button name="odr" required>Sally</mat-radio-button>
<mat-radio-button name="odr" required>Sue</mat-radio-button>
</mat-radio-group>
</div>
.ts
myForm = new FormGroup({
odr: new FormControl(''),
});
.css
.invalid{
color:"red";
}
So I would like the label "Our Dear Relative:" to be red when nothing is selected initially, then go back to normal if one of them is checked. Currently, this code does not turn the label red.
CodePudding user response:
The label is not red because your control doesn't have any validators.
This should fix your issue
myForm = new FormGroup({
odr: new FormControl(null, Validators.required),
});
CodePudding user response:
I think, you should try to add Validator required
, when you are creating the form, and additionally trigger updateValueAndValidity
, in that case all validators will be executed and your label will be red
myForm = new FormGroup({
odr: new FormControl('', [Validators.required]),
});
myForm.updateValueAndValidity();