Search code examples
htmlcssangularformsangular-directive

How to make angular radio group label red if nothing selected?


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.


Solution

  • All three of these files contain errors, especially the html file. So I'm just going to give you the right way to set it up.

      myForm = new FormGroup({
        odr: new FormControl('', Validators.required),
      });
    
    <form [formGroup]="myForm">
      <div>
        <label for="odr" [ngClass]="{ invalid: myForm.get('odr')?.invalid }">
          Our Dear Relative:
        </label>
      </div>
      <mat-radio-group id="odr" formControlName="odr">
        <mat-radio-button value="Sally">Sally</mat-radio-button>
        <mat-radio-button value="Sue">Sue</mat-radio-button>
      </mat-radio-group>
    </form>
    
    .invalid {
      color: red;
    }
    

    (no quotes around red)