Search code examples
angularangular-materialionic4angular8mat-table

Mat Table -How to select only one mat radio button in column of radio buttons


How to set mat radio button when we make a primary that contact detail then save it shown on (image 1) image1

Shown (image 2) when we get detail on the click of Save button

image2

then shown on mat table (image 3) I want set selected only one radio button on getting the primary true before image shown

image3

there is a code for Mat radio button on the mat table

<ng-container matColumnDef="primary" sticky>
                <th mat-header-cell *matHeaderCellDef>Primary </th>
                <td mat-cell *matCellDef="let element;">
                  <mat-radio-group> 
                    <mat-radio-button></mat-radio-button>
                  </mat-radio-group>
                </td>
              </ng-container>

Solution

  • Handle click of each radio button to get the selected radio button. To make only one checked in column of radio buttons check whether current element's id is equal to selected one's id [checked]="primaryContact.id == element.id"

    Modify your radio button template to template below

    <ng-container matColumnDef="primary" >
                <th mat-header-cell *matHeaderCellDef>Primary </th>
                <td mat-cell *matCellDef="let element;">
                    <mat-radio-button (click)="primaryClick(element)"
                   [checked]="primaryContact.id == element.id" ></mat-radio-button>
                </td>
       </ng-container>
    

    and in ts create instance variable to hold the current contact which is selected as primary. To avoid errors set its value to first row of data.

     primaryContact={primary:false,name:'snfjn',mobile:328754,email:'@fndn',...your fields};
    

    and now handler function for setting the primaryContact to selected radiobutton's element

      primaryClick(element){
            this.primaryContact=element;
            console.log(this.primaryContact.name)
          }
    

    Stackblitz : https://stackblitz.com/edit/material-table-demo-wjpqsy