MatSnackBar in Angular Material
Last Updated :
23 Feb, 2021
Angular Material is a UI component library developed by Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have done it you can enter the below command and can download it. MatSnackBar is used to display information or text from bottom of the screen when performing any action.
Installation syntax:
ng add @angular/material
Approach:
- First, install the angular material using the above-mentioned command.
- After completing the installation, Import ‘MatSnackBarModule’ from ‘@angular/material/snack-bar’ in the app.module.ts file.
- First we need to create an instance for ‘MatSnackBar’. Then we need to invoke a function on button click.
- Using this instance we get access to open() function which is in-built.
- Now we need to mention the duration of the message.
- Once done with the above steps then serve or start the project.
Code Implementation:
app.module.ts
import { NgModule } from '@angular/core' ;
import { BrowserModule } from '@angular/platform-browser' ;
import { FormsModule } from '@angular/forms' ;
import { AppComponent } from './app.component' ;
import { BrowserAnimationsModule } from
'@angular/platform-browser/animations' ;
import {MatSnackBarModule} from '@angular/material/snack-bar' ;
import { MatButtonModule } from '@angular/material/button' ;
@NgModule({
imports: [
BrowserModule,
FormsModule,
MatButtonModule,
MatSnackBarModule,
BrowserAnimationsModule
],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
|
app.component.ts
import { Component } from '@angular/core' ;
import {MatSnackBar} from '@angular/material/snack-bar' ;
@Component({
selector: 'my-app' ,
templateUrl: './app.component.html' ,
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
constructor(private _snackBar: MatSnackBar) {}
openSnackBar(message: string, action: string) {
this ._snackBar.open(message, action, {
duration: 2000,
});
}
}
|
app.component.html:
HTML
< button mat-stroked-button (click)=
"openSnackBar('GAME ONE','HURRAH !!!!!')">
Show snack-bar Message
</ button >
< p >
By Clicking on above button we can invoke
the function and it will, render the
message of snack-bar
</ p >
|
Output:
Share your thoughts in the comments
Please Login to comment...