Angular Material Button Toggle

  • Button Toggle is an element with an appearance of an Button and can toggle between on and off states.
  • Button toggle can be used individually or can be used as an alternative to checkbox and radio button

material.module.ts (New Module added)

import { NgModule } from '@angular/core';
import { MatButtonModule } from '@angular/material';
import { MatButtonToggleModule} from '@angular/material/button-toggle';
import { MatIconModule} from '@angular/material/icon';


const MaterialComponent = [
  MatButtonModule,
  MatButtonToggleModule,
  MatIconModule
];

@NgModule({
  imports: [
    MaterialComponent,
  ],
  exports: [
    MaterialComponent
  ]
})
export class MaterialModule { }

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MaterialModule } from './material/material.module';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    MaterialModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html

<div>
  Status : {{toggleBtn1.checked}}
  <mat-button-toggle #toggleBtn1 class="alignCss">Toggle</mat-button-toggle>

  Status : {{toggleBtn2.checked}}
  <mat-button-toggle #toggleBtn2 checked class="alignCss">Toggle</mat-button-toggle>

</div>
<div>

</div>
<div>
  <mat-button-toggle disableRipple class="alignCss">RippleDisabled</mat-button-toggle>
  <mat-button-toggle disabled class="alignCss">Disabled Toggle Off</mat-button-toggle>
  <mat-button-toggle checked disabled class="alignCss">Disabled Toggle On</mat-button-toggle>
</div>
<div>
  Radio Button like toggle
  <mat-button-toggle-group #toggleGroup1="matButtonToggleGroup">
    <mat-button-toggle value="angular">Angular</mat-button-toggle>
    <mat-button-toggle value="react">React</mat-button-toggle>
    <mat-button-toggle value="vue">Vue</mat-button-toggle>
  </mat-button-toggle-group>
  Value : {{toggleGroup1.value}}
</div>
<div>
  Checkbox like toggle
  <mat-button-toggle-group #toggleGroup2="matButtonToggleGroup" multiple>
    <mat-button-toggle value="English">English</mat-button-toggle>
    <mat-button-toggle value="Hibru">Hibru</mat-button-toggle>
    <mat-button-toggle value="Latin">Latin</mat-button-toggle>
  </mat-button-toggle-group>
  Value : {{toggleGroup2.value}}
</div>
<div>

</div>

app.component.css

mat-button-toggle.alignCss{
  margin-right: 3rem;
}

Leave a Comment