"Utilizing Angular's dynamic variable feature to apply ngClass dynamically

Looking for guidance on Angular - color change on button click.

The loop binding is functioning well with dynamic variable display in an outer element like {{'profile3.q2_' + (i+1) | translate}}, but facing issues with [ngClass] variable binding.

How can I use the " [ngClass]='q2_' + (i+1) =='1'? ~~~ " part effectively?

Your help is appreciated.

*.html file

If not using dynamic variables:

<ion-row class="ion-margin-top ion-margin-bottom">
   <ion-col size="4"> 
     <ion-button expand="block" fill="outline" 
       [ngClass]="'q2_1 =='1'?'btn-background' : 'btn-default'" (click)="onClicked(1)">
          <span class="contentText">{{'profile3.q2_1' | translate}}</span> 
     </ion-button>  
   </ion-col> 
   <ion-col size="4"> 
     <ion-button expand="block" fill="outline" 
       [ngClass]="'q2_2 =='1'?'btn-background' : 'btn-default'" (click)="onClicked(2)">
          <span class="contentText">{{'profile3.q2_2'| translate}}</span> 
     </ion-button>  
   </ion-col>
 </ion-row>
 
 ~~ 

Preferred approach (using dynamic variable and condition):

<ion-row class="ion-margin-top ion-margin-bottom">
   <ion-col size="4" *ngFor='let in of counter(7) ;let i = index'> 
     <ion-button expand="block" fill="outline" 
       [ngClass]="'q2_' + (i+1) =='1'?'btn-background' : 'btn-default'" (click)="onClicked(i+1)">
          <span class="contentText">{{'profile3.q2_' + (i+1) | translate}}</span> 
     </ion-button>  
   </ion-col> 
 </ion-row> 

*.ts file :

public q2_1 : string = "0";  
public q2_2 : string = "0"; 
~~ 

counter(i: number) {
  return new Array(i);
} 

onClicked(opt){
  if (opt == 1) this.q2_1=this.q2_1=='0'? '1': "0";  
  if (opt == 2) this.q2_2=this.q2_2=='0'? '1': "0"; 
  ~~~~ 
} 
...  

------------------------

 

Answer №1

Unfortunately, directly referencing variables dynamically in this way may not work as expected. However, there are simple workarounds available to achieve the desired result. If you prefer having easily accessible individual variables, you can make some minor adjustments.

.html

<ion-row class="ion-margin-top ion-margin-bottom">
   <ion-col size="4" *ngFor='let in of counter(7) ;let i = index'> 
     <ion-button expand="block" fill="outline" 
       [ngClass]="q2[i].val === '1' ? 'btn-background' : 'btn-default'" (click)="onClicked(i+1)">
          <span class="contentText">{{'profile3.q2_' + (i+1) | translate}}</span> 
     </ion-button>  
   </ion-col> 
 </ion-row> 

.ts

public q2_1 = { val: '0' };
public q2_2 = { val: '0' };

public q2 = [this.q2_1, this.q2_2];

counter(i: number) {
  return new Array(i);
}

onClicked(opt) {
  if (opt == 1) this.q2_1.val = this.q2_1.val == '0' ? '1' : '0';
  if (opt == 2) this.q2_2.val = this.q2_2.val == '0' ? '1' : '0';
}

The reason for changing q2_1 and q2_2 into objects is to create object references. This ensures that updating the variable directly will also reflect changes in the q2 array. Using plain strings would create new references and not update the array when the variable is changed.

If you are open to simplifying and removing individual variables, you can modify the .ts file as follows:

public q2 = ['0', '0'];

counter(i: number) {
  return new Array(i);
}

onClicked(opt) {
  this.q2[opt] = this.q2[opt] == '0' ? '1' : '0';
}

Remember to update the click handler from onClicked(i+1) to onClicked(i)

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

Creating a list in an Angular class: A step-by-step guide

In my Angular class, I have set up the username and password fields. Now, I want to include a list of roles as well. How can I go about adding this list of roles? export class User { userid: number; username: string; password: string; ro ...

How can you run a function in JavaScript or TypeScript that is stored as a string?

Is there a way to call a function that is stored as a string? For example: var dynamicFun = `function Hello(person) { return 'Hello' + person; }` In this case, the dynamicFun variable can store any function definition dynamically, such as: var ...

Creating smooth transitions between different components in Ionic 2 through animations

I have two components in my application. I am looking to create an animated transition between these pages. Specifically, I want to implement a flipping effect where page 1 transitions into page 2. Is there a plugin available for achieving this in Ionic ...

Unexpected behavior: ng2-dragula modelDrop event leading to undefined array

Struggling to figure out the issue with this code. As shown in this GIF, when dragging a div from one container to another, the object disappears and the array becomes undefined. https://i.stack.imgur.com/TELyc.gif Here is the code snippet: Main View.ht ...

Retrieve the component's name using ReactElement.type.name

In my current project, I am working with React and Typescript. I need to retrieve the name of a functional component, which I have discovered can be accessed through the 'type' property of the component like this: component.type.name. Initially, ...

Ways to mock a static method within an abstract class in TypeScript

Having a difficult time testing the function Client.read.pk(string).sk(string). This class was created to simplify working with dynamoDB's sdk, but I'm struggling to properly unit test this method. Any help or guidance would be greatly appreciate ...

The Angular service is sending back the error message "undefined" when trying to retrieve data with the ID parameter from the requested

When calling a service from a component, I am encountering a 400 bad request error with the following message: "Invalid data 'undefined' for parameter id" It's worth noting that the getProduct method in the API is functioning correctly. ...

"Enhance your database with Firebase's dynamic features for adding and removing

Within my firebase database, I have the following data structure: -ActionSheet -PendingApproval -SomeKey1 -someData -someData -someData -SomeKey2 -someData -someData ...

Objects vanish 10 seconds after appearing [Angular2, *ngFor]

My Angular2 template is quite straightforward: <span *ngFor="let item of items"> {{ item.description }} </span> Here is the TypeScript logic for it: let list = new Map(); for(let j = 0; j < 100; j++) { list.set(j, { description: j.toS ...

Switch the sidenav content dynamically in Angular 2 based on the current router state

Currently, I am in the process of developing a single page application using Angular 2. Within this project, I have implemented angular material mat-sidenav and mat-toolbar components. The toolbar includes a sidenav toggle button, as well as buttons that a ...

Unable to iterate over property in Angular 6 after receiving response

Recently, I started working with Angular and encountered an issue while trying to loop through a property in the component file. I kept receiving an error message stating that the property length is undefined. Check out this screenshot from Chrome DevTool ...

How can I ensure that all the text is always in lowercase in my Angular project?

Is there a way to ensure that when a user enters text into an input field to search for a chip, the text is always converted to lowercase before being processed? Currently, it seems possible for a user to create multiple chips with variations in capitaliza ...

Move the files created by ng build in the specified output directory to a different location

I am facing an issue with my Angular project. Whenever I run the ng build command, the build artifacts are generated in the dist folder as we have specified "outDir": "dist" in angular-cli.json. However, I then have to manually copy these files from the di ...

API rest data retrieval service in Angular

I'm currently working on my first Angular App and I need to fetch data from another local API Rest. My project is inspired by the Angular tutorial tour-of-heroes. I have created a component service to make API calls and display the results in another ...

Leverage the Node Short ID library in conjunction with Angular 6 using TypeScript

I attempted to utilize the node module within an Angular 6 typescript environment. Step one: npm i shortid Within my TypeScript class: import { shortid } from 'shortid'; let Uid = shortid.generate(); However, I encountered an error stating ...

Electron and React: Alert - Exceeded MaxListenersWarning: Potential memory leak detected in EventEmitter. [EventEmitter] has 21 updateDeviceList listeners added to it

I've been tirelessly searching to understand the root cause of this issue, and I believe I'm getting closer to unraveling the mystery. My method involves using USB detection to track the connection of USB devices: usbDetect.on('add', () ...

When retrieving data from MongoDB, an error occurs stating "Unable to read the property 'firstname' of null."

I've been working on retrieving user information from MongoDB and displaying it through HTML, but I keep encountering an error that says: "Cannot read property 'firstname' of null." For my backend service, I'm using Express and Node.js, ...

Comparing strings with data in objects using Angular

all. I have a query. What is the optimal method for comparing data? For instance, if you have a constant response = 225235743; And I aim to locate and exhibit all data in an object with the same ID as the one in this response. This needs to be resolved ...

There was an unfortunate parsing failure in the module: An unexpected token appeared at position 4

I need help adding the FULLCALENDAR feature to my Angular v14 project. Despite going through all the necessary setup steps, I encountered an unexpected error. Can anyone provide guidance on how to resolve this issue? package.json "@fullcalendar/angul ...

What is the best way to designate external dependencies in WebPack that are not imported using '*'?

I need assistance with specifying office-ui-fabric-react as an external dependency in my TypeScript project using Webpack. Currently, I am importing only the modules I require in my project: import { Dialog, DialogType, DialogFooter } from 'office-u ...