Creating alerts in Angular using EventEmitter

I am in the process of building an Angular application and I have a requirement to implement alerts. These alerts should be displayed in response to POST/PUT/DELETE requests, showing a success message. Previously, I achieved this by creating a class:

export class Alert{
    "status" : boolean;
    "text": string;
    constructor(){
        this.status=false;
        this.text="";
    }
    public setAlert(text){
        this.status = true;
        this.text = text;
    }
    public close(){
        this.status = false;
    }
}

Followed by the HTML:

<div *ngIf = "alert.status"  class="alert alert-success 
            alert-dismissible fade show" role="alert">
              <button type="button" class="close" data-dismiss="alert" aria-label="Close"
              (click) = "alert.close()">
                <span aria-hidden="true">&times;</span>
              </button>
              {{alert.text}}
            </div>

and in the component.ts file:

import { Alert } from './alert';

  alert: Alert;

  ngOnInit() {

    this.alert = new Alert();

  }

  editForm() {

    fetch(this.formService.formsUrl + "/" + this.formService.form.id, {

      method: 'PUT',

      body: JSON.stringify(this.formService.form),

      headers: {

        "Content-type": "application/json; charset=UTF-8"

      }

    })

    .then(response => response.json())

    .then(json => console.log(json));

    this.alert.setAlert("Post has been successfully saved !");

  }

I was advised that using EventEmmiter is a better approach for implementing alerts. Can you provide guidance on how to proceed with this method?

Answer №1

It is not typical to create this from scratch, instead, developers often rely on pre-existing libraries for message displays. One popular option is the snackbar provided by Angular Material.

Answer №2

Expanding on Julien's response, I recommend creating a custom notification service to manage the various types of notifications required in your application. By calling this service to display notifications, you can easily update and modify the notification behavior without altering multiple components.

import { Injectable } from '@angular/core';
import { MatSnackBar, MatSnackBarRef } from '@angular/material';

@Injectable({
  providedIn: 'root'
})
export class NotificationService {

  constructor(public snack: MatSnackBar) { }
  showNotification(message: string, action: any, duration: number): MatSnackBarRef<any> {
    return this.snack.open(message, action, { duration: duration , verticalPosition: 'top', horizontalPosition: 'right'});
  }
}
Simply inject the NotificationService into your components and utilize the showNotification method, which can be customized according to your specific requirements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The parameter type '==="' cannot be assigned to the 'WhereFilterOp' type in this argument

I'm currently working on creating a where clause for a firebase collection reference: this.allItineraries = firebase .firestore() .collection(`itinerary`); Here is the issue with the where clause: return this.allItiner ...

The power of Ionic 2 combined with the Web Audio API

I am currently developing an Ionic 2 application that requires access to the user's microphone. When working on a web platform, I would typically use the following code snippet to obtain microphone access. navigator.getUserMedia = (navigator['ge ...

Issue with CSS files in Jest"errors"

I'm currently facing an issue while trying to pass my initial Jest Test in React with Typescript. The error message I am encountering is as follows: ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){.App ...

How to Remove onFocus Warning in React TypeScript with Clear Input Type="number" and Start without a Default Value

Is there a way to either clear an HTML input field of a previous set number when onFocus is triggered or start with an empty field? When salary: null is set in the constructor, a warning appears on page load: Warning: The value prop on input should not ...

Angular relative routes are failing to function

I am currently working on implementing a feature module in my project and following the documentation provided. My crisis-routing.module file looks like this: import { NgModule } from '@angular/core'; import { Routes, RouterModule } from ' ...

Animating targeted elements in Angular 2

I am working with 2 components: The first component contains a router-outlet where pages with a question and 3 possible answers are injected. The second component is a preview that consists of 20 boxes. I utilize a shared service (BehaviorSubject) fo ...

Is my unit testing for the angular material data table with an expansion panel running properly and detecting the completion of animation?

I am facing an issue with testing a large reusable component that wraps the material data table. The challenge lies in verifying the logic responsible for setting the initial state (open/closed) of each expansion row. I suspect that either the click event ...

Creating a custom pipe that converts seconds to hours and minutes retrieved from an API can be achieved by implementing a transformation function

Can someone please provide guidance on creating a custom pipe in Angular 8 that converts seconds to hours and minutes? Thank you. <div class="col-2" *ngFor="let movie of moviesList"> <div class="movie"> {{ movie.attributes.title }} ...

Please come back after signing up. The type 'Subscription' is lacking the specified attributes

Requesting response data from an Angular service: books: BookModel[] = []; constructor(private bookService: BookService) { } ngOnInit() { this.books = this.fetchBooks(); } fetchBooks(): BookModel[] { return this.bookService.getByCategoryId(1).s ...

Stepping up the Angular AuthGuard game: Harnessing CanMatchFn and CanActivateFn for ultimate security (Class Guards make way for Functional Guards)

I have developed an Angular AuthGuard component as shown below: @Injectable({ providedIn: 'root', }) export class AuthGuard implements CanActivate, CanLoad { constructor(private authService: AuthService, private router: Router) {} ca ...

Is it possible to create a QR Code using Ionic 5?

Is there a way to generate QR Codes in Ionic 5? I attempted it, but keep receiving an error stating that the qrcode element is not recognized. Here is my code: qrcode.html <ion-item> <ion-input type="text" placeholder="My QR d ...

Unable to find solutions for all parameters in AnalysisComponent: ([object Object], ?, ?, [

As a newcomer to the Angular framework, I encountered an issue when adding project services. Error: Can't resolve all parameters for AnalysisComponent: ([object Object], ?, ?, [object Object], [object Object], [object Object], [object Object], [obj ...

Angular-cli is throwing an error stating it cannot locate the module '@ngtools/json-schema'

After running npm update in my project, I seem to be encountering an issue whenever I try to run ng serve. Error: Cannot find module '@ngtools/json-schema' Oddly enough, the @ngtools file is clearly present in my node_modules directory. I&apo ...

The button will be disabled if any cells in the schedule are left unchecked

I am seeking help on how to dynamically disable the save button when all checkboxes are unchecked. Additionally, I need assistance with enabling the save button if at least one hour is selected in the schedule. Below is my code snippet for reference: htt ...

What could be causing the disappearance of the top and bottom lines in jquery datatable after the data details are

After setting up a screen with a jquery datatable that loads correctly, I noticed an issue. When I edit the details of a record and return to the table, only the row containing the table is visible. Here is my table declaration: $(document).ready(() => ...

Unnecessarily intricate: A Comparison and Enumeration of Elements in Arrays

I am facing a challenge with organizing arrays that represent categories and subjects. Each array represents a category, while each item within the array is a subject. For example: 4 Categories with Subjects ['A','B','D'] [&a ...

Angular's Dynamic Injection: Introducing a new component into its parent component

I am looking for guidance on injecting a component dynamically into another in Angular 4, as well as passing values from the parent component to the child component. If anyone can provide a sample of working code, it would be greatly appreciated. ...

Guide on assigning a class to an array of JSON objects in TypeScript

If I have an array of JSON objects, how can I cast or assign the Report class to it? console.log('jsonBody ' + jsonBody); // Output: jsonBody [object Object],[object Object] console.log('jsonBody ' + JSON.stringify(jsonBody)); // Outpu ...

What could be causing the HTTP response Array length in Angular to be undefined?

Currently, I am facing an issue while retrieving lobby data from a Spring Boot API to display it in my Angular frontend. After fetching the data and mapping it into an object array, I encountered a problem where the length of the array turned out to be und ...

To access the Angular application using oidc-client.js, users must first login in a separate tab

My Angular 8 application is using authorization handled by (oidc-client.js) + .Net Core IdentityServer4. Although everything seems to be working fine, I encounter an issue when opening the same application in a second tab - it requires me to login again. ...