Using the "as" keyword in Angular for assigning variables within HTML documents

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');
  }
}

Answer №1

To switch things up, all you have to do is change the sequence of expressions. Instead of having it like this:

<h2 *ngIf="('HOME.TITLE' | translate | uppercase as title) && displayTitle">{{ title }}</h2>

You should rearrange it as follows:

<h2 *ngIf="displayTitle && ('HOME.TITLE' | translate | uppercase) as title">{{ title }}</h2>

See a live example here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps to authorize an API request using a token

I have an API that requires authentication using a token. In Swagger UI, I am able to authenticate this API by providing the token in the authorize section. For example, if I input "Token 6ec8f4023d8148209749a1ed972xxxx" in the authorization box Here is ...

Error in Typescript: Issue with Object.fromEntries Typescript Error

In my TypeScript code, I have a function that utilizes Object.fromEntries to simplify a complex response object and organize it by using a substring of the child object key. let Newresult = res.map(object => Object.fromEntries(Object.entries(object).ma ...

custom field component for react-hook-form

I have been working on creating a form field component that can be utilized at both the root form level and as a nested field. export type FirstNameField = { firstName: string; }; type GenericFormType<T, NS extends string | never = never> = NS ext ...

`The enforcement of a function's parameter requiring it to be part of the generic type T`

Is there a way in my typescript function to ensure that all keys in the second argument belong to the object defined by the first argument? For example: mapTo([new KeyValue('a', 'b'), new KeyValue('x', 'y')], {key ...

Struggling to pass images from express to Angular6

Snippet of Node.js code app.use('/static/images',express.static(path.join(__dirname,'images'))) Folder Structure |-root | -images When attempting to fetch data in my Angular6+ application, I am utilizing the following ...

Cypress - AG-Grid table: Typing command causing focus loss in Cell

Encountering a peculiar issue: I am attempting to input a value into the cell using 'type()'. My suspicion is that each letter typed causes the focus on the cell to be lost. It seems that due to this constant loss of focus and the 'type()& ...

Exploring potential arrays within a JSON file using TypeScript

Seeking guidance on a unique approach to handling array looping in TypeScript. Rather than the usual methods, my query pertains to a specific scenario which I will elaborate on. The structure of my JSON data is as follows: { "forename": "Maria", ...

Triggering TypeScript error due to missing type annotations for arrays

When I type const array = [], TypeScript automatically infers it as any[]. I have been looking for a solution to make this fail linting, but so far I have not found any rule in either ESLint or TypeScript that can help with this. const array = []; //arra ...

Working with Angular: Managing an Array of Objects

After retrieving an array of objects using the code snippet below: this.serviceOne.getRemoteData().subscribe( data => this.MyArray.push(data) ); I encounter issues when trying to iterate through the array using the code snippet bel ...

Refactoring TypeScript components in Angular

How can I streamline the TypeScript in this component to avoid repeating code for each coverage line? This angular component utilizes an ngFor in the HTML template, displaying a different "GroupsView" based on the context. <div *ngFor="let benefitG ...

Encountering the ExpressionChangedAfterItHasBeenCheckedError message despite updating the property via the @Output event

Attempting to update a property on the parent component through an event in the child component has proved challenging. Research suggests that this can be achieved using @Output as it is the recommended method to transmit data from child component to pare ...

Rendering multiple components in an array with React

I am trying to utilize the React MUI AccordionDetails component to display each element from the targetTypeData array, which always has a fixed length of 6 elements. Each element in the array consists of a Typography component. While my current approach s ...

Tips for concealing information within the column labeled company Name with respect to the field designated as Company Name

I am currently working on an Angular 7 app and I am facing an issue: I cannot hide the data in the column for Company Name. The field "Name" in the report control JSON is labeled as Company Name. The report control is a table that contains various fields ...

Angular - A simple way to conceal a specific row in a mat-table using Angular

I am looking to dynamically hide or show a specific column in a table by clicking on a button. The goal is to hide or delete the weight column when the "hide weight" button is clicked, and then show the weight column when the "show weight" button is clicke ...

What is the correct way to extract a value from a keyvalue pair?

When dealing with an object that returns boolean "issues", I specify it as a string. If the value is true, I aim to show a checkmark; if false, I want to display a cross. <ul *ngFor="let filtered of reposFiltered | keyvalue"> <li *ngIf=& ...

Utilize mui-tiptap to effortlessly upload images to your content

My current project involves using the mui-tiptap module in React 18 with Vite. Specifically, I am facing an issue with uploading a local image to my backend. The problem seems to lie in my frontend code, as I am encountering a TypeScript error that is prev ...

How to highlight a specific date in angular 10's mat-date-range-input using a specific

Currently, I am working on a project that involves integrating the MatDatePicker component from Angular Material to create a customized calendar for specific dates. However, I have run into an issue when trying to add custom CSS classes to certain calendar ...

Tips for showcasing unique validation error messages

My form includes a text area for the user to input JSON Code. If the entered text is not valid JSON, an error message should be displayed but unfortunately, it's not working as expected. Below is my custom validator code: import { AbstractControl, V ...

Ways to make a GET request with a parameter

I'm currently working on a basic MEAN application, but I'm encountering an issue with a GET method. After adding some data to my mongo collection, I'm trying to retrieve all results by passing the ID as a parameter. However, Angular is givi ...

Submit numerous queries to verify the presence of a name and assign it to the name attribute

I have a collection of unique devices. As part of a process, I need to assign a default name to each device ("DeviceX" - where X is a sequential number), but some of the names may already be in use. To handle this, I must make a request to check ...