Skip to content

Instantly share code, notes, and snippets.

@adrianriepl
Created June 12, 2018 14:27
Show Gist options
  • Save adrianriepl/78b2d73473848ce4d09290bb3eb022ef to your computer and use it in GitHub Desktop.
Save adrianriepl/78b2d73473848ce4d09290bb3eb022ef to your computer and use it in GitHub Desktop.
Custom translatable component using ngx-translate for ngx-toastr
<!-- Close button -->
<button *ngIf="options.closeButton" (click)="remove()" class="toast-close-button" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
<!-- Title of the toast -->
<div *ngIf="title" [class]="options.titleClass" [attr.aria-label]="title">
{{ title | translate }}
</div>
<!-- Message of the toast when HTML is enabled, only supports translations without parameters -->
<div *ngIf="message && options.enableHtml" role="alertdialog" aria-live="polite"
[class]="options.messageClass" [innerHTML]="message | translate">
</div>
<!-- Message of the toast -->
<div *ngIf="message && !options.enableHtml" role="alertdialog" aria-live="polite"
[class]="options.messageClass" [attr.aria-label]="message">
{{ message | translate }}
</div>
<!-- Progress bar-->
<div *ngIf="options.progressBar">
<div class="toast-progress" [style.width]="width + '%'"></div>
</div>
import { Component } from '@angular/core';
import { trigger, style, state, transition, animate } from '@angular/animations';
import { Toast, ToastrService, ToastPackage } from 'ngx-toastr';
@Component({
selector: '[translatable-toast]',
templateUrl: './translatable-toast.component.html',
styles: [],
animations: [
trigger('flyInOut', [
state('inactive', style({
display: 'none',
opacity: 0,
})),
state('active', style({ opacity: 1 })),
state('removed', style({ opacity: 0 })),
transition('inactive => active',
animate('{{ easeTime }}ms {{ easing }}')
),
transition('active => removed',
animate('{{ easeTime }}ms {{ easing }}'),
),
]),
]
})
export class TranslatableToastComponent extends Toast {
constructor(
protected toastrService: ToastrService,
public toastPackage: ToastPackage) {
super(toastrService, toastPackage);
}
}
@adrianriepl
Copy link
Author

A custom component for ngx-toastr which can be used to translate the content (title and message) using ngx-translate. Just pass the translation key to the ToastrService, for example:

this.toastr.success('notifications.hero.created', 'notifications.hero.title');

Also supports translatable HTML content, but only on translations without parameters, because you currently can not pass data through the ToastrService.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment