2

On click of a button inside a toast I want to close that particular toast. I want to know a way to get the toast Id inside the custom toast component Below is my code

action(btn: IToastButton) {
 enter code hereevent.stopPropagation();
 this.toastPackage.triggerAction(btn);
 this.toastrService.remove(toastID);
 return false;
}
  • Can you just add `closeButton: true` inside your custom toast in order to close the same toast? – Jeremy Jul 09 '20 at 14:57

1 Answers1

1

As per my understanding, you need the id of tostr because you need to close the toastr of that specific id. Here I have solution through which you can customize the toastr as you want.

To do so you need to make a CUSTOM TOASTR COMPONENT & initialize in toastr.

component.html

<!-- custom toastr -->
<div class="row" [style.display]="state.value === 'inactive' ? 'none' : ''">
  <div class="col-9">
    <div *ngIf="title" [class]="options.titleClass" [attr.aria-label]="title">
      {{ title }}
    </div>
    <div *ngIf="message && options.enableHtml" role="alert" aria-live="polite"
      [class]="options.messageClass" [innerHTML]="message">
    </div>
    <div *ngIf="message && !options.enableHtml" role="alert" aria-live="polite"
      [class]="options.messageClass" [attr.aria-label]="message">
      {{ message }}
    </div>
  </div>
  <div class="col-3 text-right">
    <a *ngIf="options.closeButton" (click)="remove()" class="btn btn-sm font-medium-3">
      &#10005;
    </a>
  </div>
</div>
<div *ngIf="options.progressBar">
  <div class="toast-progress" [style.width]="width + '%'"></div>
</div>
<!--/ custom toastr -->

component.ts

import { Component } from '@angular/core';

import { Toast, ToastrService, ToastPackage } from 'ngx-toastr';
import { toastrSlideY } from './custom-toastr.animation';

@Component({
  selector: '[app-custom-toastr-component]',
  templateUrl: './custom-toastr.component.html',
  animations: [ toastrSlideY ],
  preserveWhitespaces: false
})
export class CustomToastrComponent extends Toast {

  constructor(
    protected toastrService: ToastrService,
    public toastPackage: ToastPackage
  ) {
    super(toastrService, toastPackage);
  }

}

toastr.component.ts

  // initializing custom toastr 
  toastr() {
    const customToastrRef = cloneDeep(this.options);
    customToastrRef.toastComponent = CustomToastrComponent;
    customToastrRef.closeButton = true;
    customToastrRef.tapToDismiss = false;
    this.toastr.success(
      'Have fun storming the castle!',
      'Slide Down / Slide Up!',
      customToastrRef
    );
  }

toastr.component.html

<button class="btn btn-outline-warning" (click)="toastr()">Toastr</button>

NOTE: make sure you add custom component in entery component like this:

module.ts

declarations: [
ToastrComponent,
CustomToastrComponent,
],
entryComponents: [CustomToastrComponent]
Parth Developer
  • 1,371
  • 1
  • 13
  • 30