What is the best way to display toastr messages in an Angular application?

Can you guide me on how to include toastr in an angular app?

Currently, I am enrolled in the Angular Fundamentals course and trying to use toastr.success within my export class:

handleThumbnailClick(eventName){
    toastr.success(eventName)
}

But, I keep encountering this error:

https://i.sstatic.net/VPOGb.png

Here's the content of my ts file:

import { Component, OnInit } from '@angular/core'
import { EventService } from './shared/event.service'

declare let toastr

@Component({
    selector: 'events-list',
    template: `<div>
                    <h1>upcoming angular components</h1>
                    <hr>
                    <div class="row">
                        <div class="col-md-5" *ngFor="let event of events">
                            <event-thumbnail (click)="handleThumbnailClick(event.name)" [event]="event"></event-thumbnail>
                        </div>
                </div>

</div>`})
export class EventsListComponent implements OnInit   {
    events:any[]
    constructor(private eventService: EventService) {
    }

    ngOnInit() {
        this.events = this.eventService.getEvents()
    }

    handleThumbnailClick(eventName){
        toastr.success(eventName)
    }
}

I have used npm install toastr --save to install toastr and made the necessary modifications in the angular.json file:

https://i.sstatic.net/EO2NO.png

Any insights on why toastr is not displaying correctly?

Answer №1

Make sure to include this import statement:

import * as toastr from 'toastr';

instead of:

declare let toastr

Also, update your angular.json file to include the following:

        "styles": [
          "src/styles.css",
          "../node_modules/toastr/build/toastr.min.css"
        ],
        "scripts": [
          "../node_modules/toastr/build/toastr.min.js"
        ]

Answer №2

That solution seems to be a good fit for the issue at hand. Please remember to execute the following steps:

  1. npm i --save-dev @types/toastr
  2. Include the necessary paths in angular.json file
"styles": [
    "node_modules/toastr/build/toastr.min.css"
],
"scripts": [
    "node_modules/toastr/build/toastr.min.js"
]
  1. Instead of declaring let toastr, use
    import * as toastr from 'toastr';

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

Vue.js Enhances CoolLightBox with Multiple Galleries

I am trying to set up a page with multiple galleries using CoolLightBox. It worked fine for me when I had just one gallery, but now that I want to create multiple galleries - each with its own image on the page - it is only displaying one image in the ligh ...

Displaying an external webpage within a Backbone application

Is it feasible to display an external webpage in a view by using its URL? I am working with Backbone and Handlebars. var AuthorizeInstagramView = Backbone.View.extend({ template: Handlebars.compile(template), initialize: function () { }, ...

Obtain the current state of an Angular Material radio button that has been selected

I am currently working with an Angular Material mat-table that has columns for checkboxes and rows, using Material components for each. Extracting the selected state of the checkbox is straightforward with row.checked, as demonstrated below. However, I am ...

Using Vue 3 to have the ability to include multiple composable instances in a single script tag

Currently in the process of revamping our components that are originally built using the Options API. A key point for refactoring from a code-cut perspective is how we handle our multiple modals, each with their own open/close and boolean logic scattered t ...

handlebars.js template to check the condition based on the last item in an array

I am currently utilizing handlebars.js as my templating engine and am interested in creating a conditional segment that will only display if it happens to be the final item within an array located in the templates configuration object. { columns: [{< ...

Exploring SubjectBehavior within my UserService and Profile Component

Within my ShareService, I have the following code snippet: isLogin$:BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false); <==== default value is false CheckUser = this.isLogin$.asObservable(); public isLogin (bool){ ...

What are the best scenarios for implementing PHP(cURL) instead of JavaScript (Axios, Ajax, Fetch)?

When deciding between using a JavaScript program or a PHP one to interact with a web API for making HTTP requests such as POST and GET, which option would be more suitable? ...

Issue with retrieving data from MySQL database using PHP in Chart.js

I am currently facing an issue while trying to populate a chart using the ChartJS plugin with data from my MySQL database. I keep encountering the error message: mysqli_fetch_assoc(): Couldn't fetch mysqli_result in ... Despite using json_encode, ...

Is there a distinction in invoking a service through reference or directly in Dependency Injection?

QUERY: Are there any discernible differences between the two instances of utilizing a factory service? Instance 1: angular.module('ramenBattleNetworkApp') .controller('MainCtrl', function ($scope, Helpers) { var testArray = [1 ...

Displaying an array object within an array of objects in Angular 2: A guide

Here is an example of a JSON file: { "id": 5, "url": "http://localhost:8000/api/v1/users/5/", "username": "Najmuddin", "email": "", "groups": [ { "id": 1, "url ": "http://localhost:8000/api/v1/groups/1/", ...

Tips on including text within PrimeNG speeddial option buttons?

Instead of icons, I would like to have text displayed in the options of my speed dial component. https://i.sstatic.net/I4Rx5.png This is what I am aiming for https://i.sstatic.net/0u5OP.png Thank you in advance ...

Incorporating HTTP headers into Angular 6

Could someone confirm if this method is correct for adding headers to http requests in Angular 6? Upon inspecting the call through SwaggerUI, it appears that the required headers are: url -X GET --header 'Accept: application/json' --header &apo ...

Spinning Loader in ui-select AngularJS

Currently, I am working with AngularJs and the ui-select plugin from ui-select. My goal is to implement a spinner while fetching data from the server. How can I integrate a spinner directly into the HTML code? The following snippet shows the existing HTML ...

What is the best way to utilize the select all feature in Angular Material select components?

Is it possible for anyone to utilize the array data provided in the URL below? [{"columnName":"Column 1 - Type of Medication\n Number of Medications","selected":false},{"columnName":"Column 2 - Placebo&bsol ...

The ng-token-auth plugin in combination with the ui-router resolver leads to a blank

I have been referring to the ng-token-auth documentation here in an attempt to implement a resolver for authentication using the validateUser function. However, when I add the code snippet provided in the documentation to my app.js file under the "home" st ...

Steps for loading spherical panorama image tile

Our web-based application features a spherical panorama loaded using Three.js. The texture is a 360-degree image, but as the image size increases, loading times suffer. We are interested in finding a solution to this issue by tiling the images into small ...

Scroll to the top on every Angular 5 route change

Currently, I am utilizing Angular 5 for my project. Within the dashboard interface, there are various sections with varying amounts of content. Some sections contain only a small amount of information, while others have large amounts of content. However, w ...

Javascript - Button animation malfunctioning after first click

One issue I'm facing is with an animation that is triggered using the onmousedown event. Another function is supposed to stop the animation when onmouseup is detected. The problem arises after the first time it works correctly. Subsequent attempts to ...

determining the overall page displacement

I'm working with this code and I need help using the IF condition to check if the total page offset is greater-than 75%. How can I implement that here? function getLocalCoords(elem, ev) { var ox = 0, oy = 0; var first; var pageX, pageY; ...

How can I easily add both horizontal and vertical arrows to components in React?

Creating a horizontal line is as simple as using the following code: <hr style={{ width: "80%", border: "1px solid black" }} /> You can customize the width, length, and other properties as needed. If you want to display an arrow ...