Search code examples
angularangular-materialtogglebuttonpreventdefault

How can I require at least one to be selected for angular material toggle with multiple options?


I want the user to be able to select multiple options, but if there is only one choice, how can I prevent to select this button deselecting?

HTML:

<mat-button-toggle-group (change)="changeOpt($event)" multiple name="fontStyle" aria-label="Font Style">
    <mat-button-toggle value="opt1" [checked]="true">Opt1</mat-button-toggle>
    <mat-button-toggle value="opt2" [checked]="true">Opt2</mat-button-toggle>
    <mat-button-toggle value="opt3" [checked]="true">Opt3</mat-button-toggle>
</mat-button-toggle-group>

TS:

changeOpt(evt: any) {
    if (evt.value.length === 1) {
        // PreventDefault
    }
}

I wanted to prevent by looking at the total number of selections as above but I could not

stackblitz example


Solution

  • If you want "avoid" that no button selected -not only give an error message-:

    You need know about data binding. Angular supports one and two-way data binding. That's: the variables in .ts (the model) it's showed in the .html (the view). And change in inputs in .html can be change a variable in .ts

    So, we are using [(ngModel)] to give value to a one variable in .ts

    <mat-button-toggle-group [(ngModel)]="value" multiple 
         name="fontStyle" aria-label="Font Style">
        <mat-button-toggle value="opt1" (change)="change($event)">Opt1</mat-button-toggle>
        <mat-button-toggle value="opt2" (change)="change($event)">Opt2</mat-button-toggle>
        <mat-button-toggle value="opt3" (change)="change($event)">Opt3</mat-button-toggle>
    </mat-button-toggle-group>
    

    The function change, check the length of "value", if is 1, store in a variable the value, if is 0 recover the variable

    change(evt: any) {
        if (this.value.length === 1)
          this.oldValue = this.value[0];
    
        if (this.value.length === 0) 
          this.value = [this.oldValue];
    
      }
    

    See in stackblitz