'Angular "as" keyword or how to use a variable in html
I use ngx-translate in angular 13 and often have something like this in html
<div> {{ 'prefix.'+'my translation key'+'.suffix' | translate }} </div>
now, the question is that when that translation is empty, I don't want to display at all the div. I tried to use this one
<div *ngIf="'prefix.'+'my translation key'+'.suffix' | translate as myText && true">
{{ myText }}
</div>
but this does not seem to work or even compile, probably I misuse the as keyword. See here a codepen.
So my question is how to reuse the same constructs like 'prefix.'+'my translation key'+'.suffix' | translate as variable in Angular's HTML templates.
I tried also to search the Angular docs for this keyword, but didn't find that information.
PS. After some research, it seems that any second condition in the ngIf brokes 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');
}
}
Solution 1:[1]
You should just reverse the order of expressions. So instead of this:
<h2 *ngIf="('HOME.TITLE' | translate | uppercase as title) && displayTitle">{{ title }}</h2>
You should do it like this:
<h2 *ngIf="displayTitle && ('HOME.TITLE' | translate | uppercase) as title">{{ title }}</h2>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
