Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Material CheckBox with UNIQUE selection

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>
like image 886
Tobet Avatar asked Oct 19 '17 15:10

Tobet


People also ask

How do I keep my mat checkbox checked by default?

To set mat-checkbox checked by default we use checked attribute or [ngModel] as shown below. We can set the IsChecked property to true in constructor.

What is indeterminate in Mat checkbox?

<mat-checkbox> supports an indeterminate state, similar to the native <input type="checkbox"> . While the indeterminate property of the checkbox is true, it will render as indeterminate regardless of the checked value. Any interaction with the checkbox by a user (i.e., clicking) will remove the indeterminate state.

How do I use Matcheckboxchange?

Angular Material <mat-checkbox> has two events that are change and indeterminateChange . The change event is emitted when checked value of checkbox changes. The indeterminateChange event is emitted when indeterminate value of checkbox changes.


1 Answers

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

like image 122
Vega Avatar answered Sep 24 '22 14:09

Vega