Radio Button within a table with Material Design
Asked Answered
P

7

7

I'm actually trying to insert a radio button group within a table component of material design and angular 6.

So in the examples of Material design official website there is a table with checkboxes but what I want is to do the same with radio button for each element of the table.

I tried to do it with a *ngFor directive but i can't access the ELEMENT_DATA array even if it's a global const.

import {Component} from '@angular/core';
import {MatTableDataSource} from '@angular/material';
import {SelectionModel} from '@angular/cdk/collections';

@Component({
  selector: 'table-selection-example',
  styleUrls: ['table-selection-example.css'],
  templateUrl: 'table-selection-example.html',
})
export class TableSelectionExample {
  displayedColumns = ['select', 'position', 'name', 'weight', 'symbol'];
  dataSource = new MatTableDataSource<PeriodicElement>(ELEMENT_DATA);
  selection = new SelectionModel<PeriodicElement>(true, []);

  isAllSelected() {
    const numSelected = this.selection.selected.length;
    const numRows = this.dataSource.data.length;
    return numSelected === numRows;
  }

  masterToggle() {
    this.isAllSelected() ?
        this.selection.clear() :
        this.dataSource.data.forEach(row => this.selection.select(row));
  }
}

export interface PeriodicElement {
  name: string;
  position: number;
  weight: number;
  symbol: string;
}

const ELEMENT_DATA: PeriodicElement[] = [
  {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
  {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
  {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
  {position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
  {position: 5, name: 'Boron', weight: 10.811, symbol: 'B'},
  {position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'},
  {position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N'},
  {position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
  {position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
  {position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne'},
];
    <table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

  <!-- Checkbox Column -->
  <ng-container matColumnDef="select">
    <th mat-header-cell *matHeaderCellDef>
      <mat-checkbox (change)="$event ? masterToggle() : null"
                    [checked]="selection.hasValue() && isAllSelected()"
                    [indeterminate]="selection.hasValue() && !isAllSelected()">
      </mat-checkbox>
    </th>
    <td mat-cell *matCellDef="let row">
      <mat-checkbox (click)="$event.stopPropagation()"
                    (change)="$event ? selection.toggle(row) : null"
                    [checked]="selection.isSelected(row)">
      </mat-checkbox>
    </td>
  </ng-container>

  <!-- Position Column -->
  <ng-container matColumnDef="position">
    <th mat-header-cell *matHeaderCellDef> No. </th>
    <td mat-cell *matCellDef="let element"> {{element.position}} </td>
  </ng-container>

  <!-- Name Column -->
  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef> Name </th>
    <td mat-cell *matCellDef="let element"> {{element.name}} </td>
  </ng-container>

  <!-- Weight Column -->
  <ng-container matColumnDef="weight">
    <th mat-header-cell *matHeaderCellDef> Weight </th>
    <td mat-cell *matCellDef="let element"> {{element.weight}} </td>
  </ng-container>

  <!-- Symbol Column -->
  <ng-container matColumnDef="symbol">
    <th mat-header-cell *matHeaderCellDef> Symbol </th>
    <td mat-cell *matCellDef="let element"> {{element.symbol}} </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"
      (click)="selection.toggle(row)">
  </tr>
</table>

So with this code i want to remove the checkboxes and replace it with radio buttons.

what i tried is to put :

<mat-radio-group>
   <mat-radio-button *ngIf="let i of ELEMENT_DATA" value = i></mat-radio-button>
</mat-radio-button>

and like I said before I can't access my Array ELEMENT_DATA. I also tried to change it with dataSource.length, but nothing do.

thanks for helping.

Pedicab answered 29/5, 2018 at 13:29 Comment(0)
P
9

you can add the mat-radio-group to mat-cell and use ngModel:

<ng-container matColumnDef="radio">
  <mat-header-cell *matHeaderCellDef mat-sort-header></mat-header-cell>
  <mat-cell *matCellDef="let row">
    <mat-radio-group [(ngModel)]="selectedPerson">
      <mat-radio-button [value]="row"></mat-radio-button>
    </mat-radio-group>
  </mat-cell>
</ng-container>
Prieto answered 23/7, 2018 at 18:2 Comment(1)
Is it possible to wrap the mat-table with one mat-radio-group, instead of having one mat-radio-group for each row?Fruit
G
3

you can just add inside of the td of your table and it would work. but I got no idea how to know which radio button is selected.

 <table mat-table [dataSource]="dataSource" matSortDisableClear>

                                <ng-container matColumnDef="select">
                  <th mat-header-cell *matHeaderCellDef>
                    <mat-radio-button disabled>
                    </mat-radio-button>
                  </th>
                  <td mat-cell *matCellDef="let row">
                    <mat-radio-button (click)="$event.stopPropagation()"
                                      (change)="$event ? selection3.toggle(row) : null"
                                      [checked]="selection3.isSelected(row)"
                                      ></mat-radio-button>
                  </td>
                </ng-container>
                <tr mat-header-row *matHeaderRowDef="datadisplayedColumns"></tr>

                <tr mat-row *matRowDef="let row; columns: datadisplayedColumns;"></tr>
 </table>

typescript

  selection3 = new SelectionModel<Instruments>(false, []);

if you work in the row section you can always use let row as I did is also handy when you want to put a routerLink on your entire row

Germann answered 28/5, 2019 at 10:28 Comment(1)
I hope that this helps somebody because the original question is exactly 1 year oldGermann
T
2

This is probably too late, but thought I would chime in. I just wanted to implement this same behavior, and I found that using the SelectionModel from the CKD basically allowed me to visually replicate this behavior, even if not in a better way.

https://material.angular.io/components/table/overview#selection

It supports multi or single selection modes and you can easily put the click logic on the mat-row, along with any kind of visual styling (or even a radio button) to inform the user of the state of the current selection.

Tailgate answered 16/1, 2019 at 22:21 Comment(1)
Correcting my comment above, I used this for checkbox and worked well. For radio button I went with the below solution with ngModel. That was less complex.Interstice
H
1

Every thing you've done is correct. But, why are you trying to do *ngIf = "let i of Element_Data":

    <mat-radio-group>
        <mat-radio-button *ngIf="let i of ELEMENT_DATA" value = i></mat-radio-button>
    </mat-radio-button>.

Are you trying to do *ngFor? You can't do ' let i of Element_Data ' in *ngIf

Hatshepsut answered 9/1, 2020 at 12:33 Comment(0)
T
0

ELEMENT_DATA should be a property of the core component not a constant. Otherwise you cannot access it in html part.

Tentative answered 29/5, 2018 at 13:33 Comment(7)
Oh okok, and do you know how to do it then? with another method?Pedicab
Add this to your TableSelectionExample elementData = ELEMENT_DATA and then access it in your html *ngFor="let i of ELEMENT_DATA" I see you use the wrong syntax here replace your *ngIf with *ngFor when you try to access an array.Tentative
Oh yeah sorry, actually it's my bad, i'm using *ngFor directive. I tried what you said, but now I have nothing in my table and I have this error : ERROR TypeError: Cannot read property 'template' of undefinedPedicab
Ah now I understand what you try to achieve. You want to have one radio button within a row to select one specific row?Tentative
Yes that's what I want, for each element of my table i want to create a radio button. So for now i'm doing this : <ng-container matColumnDef="select"> <th mat-header-cell *matHeaderCellDef mat-sort-header>Option</th> <td mat-cell *matCellDef="let element"> <mat-radio-button *ngFor="let i of elem" [value]="i"></mat-radio-button> </td> </ng-container> and i add elem = ELEMENT_DATA; in my component class But i have in one line my 10 occurances of button and not just one for each element of my table.Pedicab
If you use *ngFor than angular generates multiple <mat-radio-buttons> Tags. You cannot use a mat-radio-group when you want to have your radio button inside a table. I would simply replace the checkbox with a radio button. The methods are the same (change) and [checked] are also available with radio buttons.Tentative
Humm I tried to use mat-radio-button instead of mat-checkbox but it's not working like I want.Pedicab
S
0

ELEMENT_DATA needs to be part of the class.

Try this:

import {Component} from '@angular/core';
import {MatTableDataSource} from '@angular/material';
import {SelectionModel} from '@angular/cdk/collections';

@Component({
  selector: 'table-selection-example',
  styleUrls: ['table-selection-example.css'],
  templateUrl: 'table-selection-example.html',
})
export class TableSelectionExample {
  displayedColumns = ['select', 'position', 'name', 'weight', 'symbol'];
  dataSource = new MatTableDataSource<PeriodicElement>(ELEMENT_DATA);
  selection = new SelectionModel<PeriodicElement>(true, []);

  isAllSelected() {
    const numSelected = this.selection.selected.length;
    const numRows = this.dataSource.data.length;
    return numSelected === numRows;
  }

  masterToggle() {
    this.isAllSelected() ?
        this.selection.clear() :
        this.dataSource.data.forEach(row => this.selection.select(row));
  }

const ELEMENT_DATA: PeriodicElement[] = [
  {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
  {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
  {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
  {position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
  {position: 5, name: 'Boron', weight: 10.811, symbol: 'B'},
  {position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'},
  {position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N'},
  {position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
  {position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
  {position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne'},
];
}

export interface PeriodicElement {
  name: string;
  position: number;
  weight: number;
  symbol: string;
}
Sama answered 29/5, 2018 at 14:2 Comment(0)
N
0

Try replicating the code below, worked for me

                <th mat-header-cell *matHeaderCellDef> No. </th>
                <td mat-cell *matCellDef="let row">    
                        <mat-radio-button [value]="row" (click)="radiobuttonClick(row)" color="primary"></mat-radio-button>
                </td>
            </mat-radio-group>
Nadaha answered 27/2, 2020 at 16:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.