Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically close the snack bar in angular material

I have implemented a snack bar when the user logs in he/she will get a notification from the snack bar whether the login was successful or unsuccessful. In my implementation, the snack bar appears the user can click dismiss and the snack bar will disappear. How do I auto close the snack bar?

  onSubmit() {
    this.isLoggedInError = true;
    // console.log(this.username);
    this.userService.login(this.username, this.password)
      .subscribe((res: any) => {
        // console.log(res);
        this.isLoggedInError = false;
        // console.log("HERE IS THE res")
        // console.log(res.token);
        // this.logInresponsePayload = res;
        // localStorage.setItem('username', res.username);
        localStorage.setItem('userToken', res.token);

        localStorage.setItem('userRoles', res.roles_list);
        // this.router.navigate(['/dashboard']);
        // console.log(res.token);

        // console.log(res.status_code);

        // Add ROLES : Predefine roles  add check 
        if (res.token === null ) {
          const  message = 'Wrong credentials provided!';
          this.snackbar.open(message, 'Dismiss');
          // this.router.navigate(['/']);

          // this.router.navigate(['/dashboard']);
        } else {
          // console.log("print 200")
          const msg = 'Login successfull!';
          this.snackbar.open(msg, 'Dismiss');
          this.router.navigate(['/dashboard']);
        }

        // localStorage.setItem('apps', res.apps);


      },
        (err: HttpErrorResponse) => {
          this.isLoggedInError = false;
        }
      );

  }
like image 660
Philip Mutua Avatar asked Oct 23 '25 15:10

Philip Mutua


1 Answers

You can either set the duration for each snack bar separately or set global configuration defaults:

// Single snack bar
snackbar.open('Message archived', 'Undo', {
  duration: 3000
});

// Global settings in app.module.ts
@NgModule({
  providers: [
    {provide: MAT_SNACK_BAR_DEFAULT_OPTIONS, useValue: {duration: 2500}}
  ]
})

Also good to know:

Only one snack-bar can ever be opened at one time. If a new snackbar is opened while a previous message is still showing, the older message will be automatically dismissed.

like image 183
pzaenger Avatar answered Oct 26 '25 09:10

pzaenger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!