Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
  }
}
like image 420
serge Avatar asked Mar 18 '26 19:03

serge


1 Answers

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>

Working example

like image 98
NeNaD Avatar answered Mar 21 '26 08:03

NeNaD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!