Documentation

The t pipe

Not everything can be wrapped in a component. Attributes such as placeholder or title take a string, and sometimes you need a translation in your TypeScript code. For these, use the t pipe or the translate method of the MagicTranslate service.

The t pipe

import { Component } from '@angular/core';
import { TranslatePipe } from '@magic-translate/angular';
@Component({
selector: 'app-search',
imports: [TranslatePipe],
template: `<input [placeholder]="'Search products' | t" />`
})
export class Search {}

The pipe returns the original text until the translation has loaded. Like the <t> component, it takes the language and the formality as options:

<input [placeholder]="'Your name' | t: { lang: 'fr', formality: 'formal' }" />

It also takes an id, to edit this use of the text on its own:

<button [title]="'Save' | t: { id: 'checkout-save' }"></button>

Variables

Pass values that should not be translated in v, and reference them as $name, the same as with the <t> component:

<input [placeholder]="'Search $count products' | t: { v: { count: products.length } }" />
<img [alt]="'Photo of $name' | t: { v: { name: user.name } }" [src]="user.photo" />

The text is translated once as Search {0} products, and the cached translation is reused when count changes.

Translating in code

To translate a string in TypeScript, call translate on the MagicTranslate service. It returns a promise.

import { inject } from '@angular/core';
import { MagicTranslate } from '@magic-translate/angular';
const magicTranslate = inject(MagicTranslate);
const message = await magicTranslate.translate('Your order has been placed');
// with options
const formal = await magicTranslate.translate('How are you?', {
lang: 'fr',
formality: 'formal'
});

Without the lang option, the text is translated into the current language.

translate takes variables too:

const message = await magicTranslate.translate('Your order $id has shipped', {
v: { id: order.id }
});