angulartoastsnackbarangular2-toaster

Add Hyperlink To Angular 2 Toast Message


I am using Angular 2 and I was wondering if it's possible to add a hyperlink to a toast message. I poked around online and saw some stuff that might work but I was wondering if there is a clear cut and easy way to implement this. Thanks!

Edit: Or if there is a way to navigate to a different url by clicking on a toast message


Solution

  • There are two different approaches for embedding any sort of HTML content within a toast.

    By importing BodyOutputType from angular2-toaster, you can specify either TrustedHtml or Component. The first allows you to pass the html directly into the body argument of the toast:

    import { BodyOutputType } from 'angular2-toaster';
    
    popTrustedHtmlToast() {
        var toast: Toast = {
          type: 'info',
          title: 'Here is a Toast Title',
          body: '<a target="_blank" href="https://www.google.com">Here is a Toast Body<a/>',
          bodyOutputType: BodyOutputType.TrustedHtml,
          showCloseButton: true 
        };
    
        this.toasterService.pop(toast);
    }
    

    The second allows you to pass the name of a component. The component is dynamically loaded and rendered as the toast body.

    @Component({
      selector: 'custom-component',
      template: `<a target="_blank" href="https://www.google.com">Here is a Toast Body</a>`
    })
    export class CustomComponent { }
    @NgModule({
        bootstrap: [CustomComponent],
        declarations: [CustomComponent]
    })
    export class CustomComponentModule { }
    
    popComponentToast() {
        var toast: Toast = {
          type: 'info',
          title: 'Here is a Toast Title',
          body: CustomComponent,
          bodyOutputType: BodyOutputType.Component,
          showCloseButton: true 
        };
    
        this.toasterService.pop(toast);
    }
    

    You can see both approaches in this plunker.