One common pattern I use in Angular 13 with ngx-translate
is to have HTML code like this:
<div> {{ 'prefix.'+'my translation key'+'.suffix' | translate }} </div>
The issue arises when the translation is empty - I don't want to display the div
at all. I attempted to handle this using the following approach:
<div *ngIf="'prefix.'+'my translation key'+'.suffix' | translate as myText && true">
{{ myText }}
</div>
However, it seems that this doesn't work as expected and may not even compile due to potential misuse of the as
keyword. You can check out an example on this CodePen link.
My question is how can I efficiently reuse constructs like
'prefix.'+'my translation key'+'.suffix' | translate
as a variable in Angular's HTML templates.
I also tried searching through the Angular documentation for information on this keyword but couldn't find anything helpful.
PS. Further investigation revealed that introducing any second condition in the ngIf
statement breaks the "compilation."
import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'app-root',
template: `
<div>
<h2 *ngIf="('HOME.TITLE' | translate | uppercase as titlee) && displayTitle">{{ titlee + displayTitle}}</h2>
<label>
{{ 'HOME.SELECT' | translate }}
<select #langSelect (change)="translate.use(langSelect.value)">
<option *ngFor="let lang of translate.getLangs()" [value]="lang" [selected]="lang === translate.currentLang">{{ lang }}</option>
</select>
</label>
</div>
`,
})
export class AppComponent {
public displayTitle = true;
constructor(public translate: TranslateService) {
translate.addLangs(['en', 'fr']);
translate.setDefaultLang('en');
const browserLang = translate.getBrowserLang();
translate.use(browserLang.match(/en|fr/) ? browserLang : 'en');
}
}