To create an Angular Material toggle button and use it in your TypeScript file, follow these steps:
- Import the necessary Angular Material modules in your component file. For example, if you're using Angular Material 12, you would need to import MatSlideToggleModule from '@angular/material/slide-toggle' and MatCheckboxModule from '@angular/material/checkbox'.
typescriptimport { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatCheckboxModule } from '@angular/material/checkbox';
- Add the modules to the imports array of your NgModule decorator.
typescript@NgModule({
imports: [
MatSlideToggleModule,
MatCheckboxModule
],
...
})
- Add the toggle button to your template using the mat-slide-toggle component.
html<mat-slide-toggle [checked]="true" (change)="onToggleChange($event)">
Toggle Button
</mat-slide-toggle>
- In your TypeScript file, define a function to handle the toggle button change event.
typescriptonToggleChange(event: MatSlideToggleChange) {
console.log('Toggle button state:', event.checked);
}
This function will be called whenever the toggle button's state changes, and the event object passed to it will contain the new state in the checked property. You can then use this value in your application logic as needed.
Note: The above steps are for creating a slide toggle button. If you want to create a checkbox, you can use the mat-checkbox component instead of mat-slide-toggle.