Utilizing ngIf in Angular to dynamically assign classes based on boolean properties when calling a function to explore various data types

I am facing a challenge in assigning different angular class boolean properties to an ngIf, as I have tried using ngSwitch and ngIf else with templates but they do not seem to work effectively.

In the sample dataset provided, it looks something like this:

   dataSet: [ { total: '$382734.99', clauseName: 'showTotalDollars' },
                    { total: '3.22%', clauseName: 'showPercentageData' }
              ]

The class boolean properties are defined as follows:

 showTotalDollars: boolean = true;
  showPercentageData: boolean = false;

In my angular code, I attempted the following approach which did not yield the desired results:

<div class="ng-container" *ngFor="let dataset of sales.dataset">
  <div class="ng-container" *ngIf="{{dataset.clauseName}}">
     <mat-list-item><span>{{total}}</span></mat-list-item>
  </div>
</div>

It's worth noting that ngIf does not work with interpolation.

I also experimented with:

*ngIf="getClauseName(item)"

In my typescript code

 getClause(clickedItem: string) {

   if (clickedItem.clauseName == 'showTotalDollars') {
     return 'showTotalDollars';
   }
   else if (clickedItem.clauseName == 'showPercentageData') {
     return 'showPercentageData';
   }
   ... and so on
 }

This approach also proved unsuccessful.

It appears that ngIf works with *ngIf="showTotalDollars" and *ngIf="showPercentageData" in the HTML code instead of directly assigning the name of the boolean properties from the typescript code.

I am looking for a solution where the angular code loops through each record in the dataset, checks the clauseName (of which there are many, not just 2), and dynamically assigns the corresponding class boolean property name. Something along these lines:

if (clauseName == 'showTotalDollars')
  then *ngIf="showTotalDollars";
else if (clauseName == 'showPercentageData')
  then *ngIf="showPercentageData";

After experimenting with interpolation and the getClauseName function, I am uncertain about how to achieve this.

The desired outcome is for the ngFor loop to iterate through each record in the dataset, check the clauseName indicating the data type, and dynamically set the ngIf to a specific boolean property name from the TypeScript class.

Any assistance or guidance on this matter would be greatly appreciated. Thank you.

Answer №1

Here is the correct code:

<div class="ng-container" *ngFor="let dataset of sales.dataset">
  <div class="ng-container" *ngIf="this[dataset.clauseName]">
    <mat-list-item><span>{{total}}</span></mat-list-item>
  </div>
</div>

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

Is Resharper suitable for analyzing Angular code?

I'm a beginner when it comes to Resharper. Despite reading the documentation, I still have some doubts. Is it possible to use Resharper for analyzing Angular projects or TypeScript files? If so, could you please explain how to do it? ...

Determine percentage and classification using a pair of functions

My goal is to display the level as a number along with a progress bar that ranges from 0 to 99 based on the current level. After researching online, I came across a math formula for leveling which is: constant * Math.sqrt(xp); In order to achieve this, I ...

Setting up ESLint for TypeScript with JSX configuration

I am encountering problems with TypeScript configuration. Below is the code snippet from my tsconfig.json: { "compilerOptions": { "target": "es5", "lib": [ "dom", "dom.iterable", "esnext" ], "allowJs": true, "skipLib ...

What is the best way to conceal the footer component on a homepage?

Here’s the snippet from my app.component.html file: <app-header></app-header> <router-outlet></router-outlet> <app-footer></app-footer> I am looking to hide the footer component specifically when on the /home route. ...

Retrieving array-like form data in a TypeScript file

I need assistance with passing form inputs into a typescript file as an array in an ionic application. The form is located in question.page.html <details *ngFor="let product of products;"> <ion-input type="text" [(ngModel ...

The source files are expected to be contained within the 'rootDir' directory, which is not located at 'c:/Users/hasit/Desktop/typescript/src'

Can someone assist me with separating the Src folder and public folder in my project? When I try to do it in the tsconfig.json file, I encounter this error: "'rootDir' is expected to contain all source files." I have followed instructions from a ...

What is the best ECMAScript version to select for implementing the TypeScript compiler in an Electron application?

In my Electron 5.0.6 project, I currently have es3 as the default target in my tsconfig.json file. However, I received an error message indicating that I need to upgrade to at least es6 to utilize getter/setter functionality in TypeScript. I am now contem ...

Begin by adding the sub Route at the start of the route path in Angular

How can I dynamically add a user's name to all routing pages in my Angular project when they type the URL like www.mysite.com/hisName? The desired result should be www.mysite.com/hisName/home This is the routing code I have: import { NgModule } from ...

Exploring the capabilities of the Angular 2 HTTP service

I am just beginning my journey with Angular 2. Here is a service I have created: @Injectable() export class PostsService { constructor(private http: Http) { } getAllPosts() { return this.http.get('/api/posts') .map ...

Do you have any recommendations for exporting a PDF that includes one set of data but has two rows of headings?

I've encountered a challenge. I have been using jspdf with autotable to generate simple reports consisting of one row of headings and one body of data, which has worked flawlessly so far. My current setup involves Angular 8. However, I now need to c ...

Is it Possible for the Number Array Type to Not Be Recognized as an Array?

export class ... { single: any[] = []; multi: any[] = []; view: number[] = [700, 400]; ... <Removed for brevity> } Error Message: It says 'Type 'number[]' is not assignable to t ...

Experimenting with a module reliant on two distinct services

I am facing an issue with a component that relies on a service to fetch data. The service also retrieves configurations from a static variable in the Configuration Service, but during Karma tests, the const variable is showing up as undefined. Although I ...

Obtaining a JSON file from Firebase Storage

Is it possible to retrieve a JSON file from Firebase Storage for use without needing to push it back? If so, how can I accomplish this using Angular with Firebase Storage? If not, would the Firebase database be a better option for this scenario? I have ...

Choosing the Angular5 model

I'm currently working with an Angular5 project that has a <select> element bound to an array of customers. Here's the code snippet: <select class="form-control" [ngModel]="record.customer_id" (ngModelChange)="setCustomer($event)" name=" ...

Is there a way to automatically validate all input fields as soon as a user arrives on the page and immediately clicks the button?

<form class="form-horizontal" (submit)="submit($event)" [formGroup]="formUser"> <input name="firstname" formControlName="firstName"> <input name="lastname" formControlName="lastName"> <button type="submit" class="btn btn-de ...

Why can't we import Angular 4 as a library similar to AngularJS?

Why was AngularJS introduced as a script to import in an HTML page? However, in the newer version Angular 4, we need to use a web server to launch the application? Is it because AngularJS is not considered a framework but Angular 4 is? Thank you. ...

Running a Spring Boot backend alongside multiple frontends on the same Tomcat server

I have a unique scenario where I have access to only one Tomcat server and need to set up the following components: A Spring Boot service that handles CRUD operations on a database through a REST API 2-3 distinct Angular frontends that interact with the R ...

What is the best way to utilize external module imports for SVG React components in a create-react-app project?

Understanding the Project Structure To ensure code reusability across multiple React projects, a specific project structure has been established: @foo/design: Includes design elements like raw SVG images @foo/ui: A React library based on Create React App ...

It is not always a guarantee that all promises in typescript will be resolved completely

I have a requirement in my code to update the model data { "customerCode": "CUS15168", "customerName": "Adam Jenie", "customerType": "Cash", "printPackingSlip": "true", "contacts": [ { "firstName": "Hunt", "lastName": "Barlow", ...

`Can incompatible Typescript types be allowed for assignment?`

Currently, I am faced with the challenge of sharing type definitions between my server and front-end. These definitions are stored in a separate npm package that both installations utilize. The issue arises on the front-end where variables containing Objec ...