Is there a way to hide the mat-radio-button in Angular and make the image inside it clickable instead?

Viewed 1653

This is how it looks till now Im trying to hide the radio button and use an image for male and female instead. This is the html code for the mat-radio-group:

   <mat-radio-group formControlName="gender">
            <mat-label>
              <mat-radio-button class="female-radio" value="M"></mat-radio-button>
              <img width="100" src={{imageTwo}}>
              </mat-label>
              <mat-label>
                <mat-radio-button class="female-radio" value="F"></mat-radio-button>
                <img width="100" src={{imageOne}}>
              </mat-label>
          </mat-radio-group>

And in my scss component I did:

.female-radio + img {
  cursor: pointer;
}

.mat-radio-checked + img {
  outline: 2px solid #f00;
}

What do I do to show only the images in order to select the gender?

2 Answers

Please make below changes in your component html

<mat-radio-group formControlName="gender">
  <mat-label>
    <mat-radio-button class="female-radio" value="M">
      <img width="100" src={{imageTwo}}>
    </mat-radio-button>
    </mat-label>
    <mat-label>
      <mat-radio-button class="female-radio" value="F">
        <img width="100" src={{imageOne}}>
      </mat-radio-button>
    </mat-label>
</mat-radio-group>

and add below css to the css/scss file

:host ::ng-deep .mat-radio-container {
  display: none;
}

This will display just the images and the functionality will remain as is. The value of the selected item can still be accessible in the formControlName gender.

If there have much more radio buttons then you can hide them by class name

enter image description here

<mat-radio-group class="only-image" [(ngModel)]="gender" >
  <mat-label>
    <mat-radio-button class="female-radio" value="M"></mat-radio-button>
    <img (click)="genderChange('M')"
      width="100"
      src="https://image.shutterstock.com/image-vector/male-sign-flat-illustration-vector-600w-1483957736.jpg"
    />
  </mat-label>
  <mat-label>
    <mat-radio-button class="female-radio" value="F"></mat-radio-button>
    <img
    (click)="genderChange('F')"
      width="100"
      src="https://image.shutterstock.com/image-illustration/male-icon-clipping-path-600w-135680966.jpg"
    />
  </mat-label>
</mat-radio-group>

// css

.female-radio {
   display: none;
 }
Related