Open In App

MatSnackBar in Angular Material

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:

Code Implementation:






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 { }




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:




<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:

 


Article Tags :