Home > front end >  angular mat radio group select index
angular mat radio group select index

Time:04-26

I have a radio button in a mat radio group coming from a loop , the button and card should be colored based on the selected index, but as you can see on the screenshot the radio button is selected but not colored in white

enter image description here

The radio button based on the selected index or selected radio should be like this but currently my logic does not work. Thanks for any help.

enter image description here

Any idea guys ? Thanks.

#html code

<p fxLayoutAlign="center" >Select Available Date</p>
                <mat-radio-group>
                  <mat-card style="cursor: pointer;" [ngClass]="selectedIndex === i ? 'selected-schedule-card' : ''" *ngFor="let item of schedules;let i = index;" fxLayoutAlign="start center" style="cursor: pointer;margin-bottom: 20px;">
                    <mat-radio-button  color="accent"   [ngClass]="selectedIndex === i ? 'selected-schedule-radio' : ''"   value="i"  (click)="onSelect(item , i)">
                        <mat-icon  style="margin-top:3px;margin-left:10px;">today</mat-icon> {{item.proposedDateStartString}}
                      </mat-radio-button>
                  </mat-card>
              </mat-radio-group>

#tscode

    onSelect(item:any , index:number) {
    this.selectedIndex = index;
    this.selectedItem = item;
  }

#css

.selected-schedule-radio {
    color: #ffffff;
  }
  
  .selected-schedule-card {
    background-color: #007DFF;
}

CodePudding user response:

You don't need a change event for this. Create a scope variable in your TS to hold the value, like

this.selectedDate='';

Put anngmodel binding on the mat-radio-group element.

[ngModel]="selectedDate"

That will track the selected value of the whole radio group. Then make your ngClass compare the radio's value with the selectedValue

[ngClass]="selectedDate === item.proposedDateStartString ? 'selected-schedule-radio' : ''"

All together...

<mat-radio-group [ngModel]="selectedDate">
  <mat-card style="cursor: pointer;" [ngClass]="selectedIndex === i ? 'selected-schedule-card' : ''" *ngFor="let item of schedules;let i = index;" fxLayoutAlign="start center" style="cursor: pointer;margin-bottom: 20px;">
    <mat-radio-button color="accent" [ngClass]="selectedDate === item.proposedDateStartString ? 'selected-schedule-radio' : ''" >
      <mat-icon  style="margin-top:3px;margin-left:10px;">today</mat-icon> {{item.proposedDateStartString}}
    </mat-radio-button>
  </mat-card>
</mat-radio-group>

CodePudding user response:

Make a function on the ts side and use this on your html: (click)=“onSelect(item)”

  • Related