Search code examples
angulartypescriptangular7

How to add toaster in Angular?


Any idea how to add a toaster notification when an error occurs instead of using alert. Many tutorials out there just make a tutorial when clicking a button but I want some automatization. Below is my code

saveStudentDetails(values) {
  const studentData = {};

  studentData['id'] =  values.id;
  studentData['password'] =  values.password;
  this.crudService.loginstudent(studentData).subscribe(result => {
    this.student = result;
    this.router.navigate(['/address']);
  },
    err => {
      console.log('status code ->' + err.status);
      alert('Please try again');
 });

}

Any idea how can i make an error toaster notification base on this code? Thank you


Solution

  • For display toaster use ngx-toastr library

    Steps:

    1) npm install ngx-toastr --save

    2) Follow other setups from here

    Quick Code :

    import { ToastrService } from 'ngx-toastr';
    
    constructor(private toastr: ToastrService) {}
    
    saveStudentDetails(values) {
      const studentData = {};
    
      studentData['id'] =  values.id;
      studentData['password'] =  values.password;
      this.crudService.loginstudent(studentData).subscribe(result => {
        this.student = result;
        this.router.navigate(['/address']);
      },
        err => {
          console.log('status code ->' + err.status);
          this.toastr.error('Hello world!', 'Toastr fun!');
     });