Material CheckBox with UNIQUE selection
Asked Answered
T

1

6

I'm struggling from 2 days on this problem in my angular2+bootstrap+material project.

I need to change the material design checkbox:

  • When i check a checkbox from my table, that check have to be the only one

I know that i can use a material radio button, but in that case i have another problem : i can't uncheck the radio button.

So i need to enable unique check and also check/uncheck functions.

enter image description here

I've tried the following

  • Interact with dom with document.getElement.blablabla
  • Used dom interpolation of angular 2
  • Javascript function
  • Jquery function

Here's the code of html:

<div class="row">
<div class="col-lg-12">
    <label>Ordini cliente</label>
    <mat-table #table [dataSource]="dataSource">

        <!--- Note that these columns can be defined in any order.
              The actual rendered columns are set as a property on the row definition" -->

        <!-- Select Column -->
        <ng-container matColumnDef="Select">
            <mat-header-cell *matHeaderCellDef></mat-header-cell>
            <mat-cell *matCellDef="let item"><mat-checkbox color="primary"></mat-checkbox></mat-cell>
        </ng-container>


        //OTHER COLUMNS ...

        <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
        <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
    </mat-table>


</div>

My idea was to bind the element to a click event like this

<mat-cell *matCellDef="let item"><mat-checkbox (click)="foo()" color="primary"></mat-checkbox></mat-cell>
Thun answered 19/10, 2017 at 15:12 Comment(0)
R
17

Set a property to keep track of which one is checked. And then set [checked] for only the one which is chosen. Here, for example, I keep the track with ngFor index:

<div *ngFor="let item of [1,2,3];  let i = index">
  <mat-checkbox [checked]="selected === i" (change)="selected = i">Check me!</mat-checkbox>
</div>

DEMO

Ringsmuth answered 19/10, 2017 at 16:25 Comment(5)
Worked, thanks a lot. ps: i've decided to use a normal html 5 table and then materializa the style , because in material table we don't have explicit ngFor sintax to bend at our logic.Thun
how i use binding for same ngmodel with multiple optionsAnselmi
This will throw Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'true'. Current value: 'false'.Woebegone
@B45i, could you provide a demo? It is related to your code and that error can be trown for many reasonsRingsmuth
Simple and straightforward, worked like a charm! thanks a lot.Ballarat

© 2022 - 2024 — McMap. All rights reserved.