Search code examples
javascriptangulartypescripttoastr

how to render toastr within angular?


How do you import toastr into an angular app?

I'm following the Angular Fundamentals course, and attempting to simply display toastr.success from within my export class:

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

And getting the following error:

enter image description here

The full ts file is:

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've run this to install toastr:

npm install toastr --save

And have included these in the angular.json file:

enter image description here

What am I doing wrong? Why doesn't toastr render?


Solution

  • Use this import statement

    import * as toastr from 'toastr';
    

    instead of

    declare let toastr
    

    and your angular.json, it should be like this

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