What is the way to assign a variable to ngClass in Angular?

I'm currently working on creating modals that will display different content based on which button is clicked. Each button should trigger a unique modal to appear, each with its own specific content inside. When a button is clicked, the 'active' property is set to true. If the value of 'active' is true, then the modal div receives the class .open.

HTML:

<button type="button" class="btn btn-4" (click)="myFunction(0)">ბანკი</button>
    <div class="modal"  [ngClass] = "**active[0].active1** ? 'open' : ''" >
      <div class="text">gfdgdgd</div>
      <button type="button" class="btn close" (click)="close()"><i class="fas fa-times-circle"></i></button>
    </div>

Typescript:

    active: any =  [
  {
    active1:false,
  },
  {
    active1:false,
  },
  {
    active1:false,
  },
  {
    active1:false,
  },
];
  constructor() { }
  


  ngOnInit(): void {
  }
  
 myFunction(id:any){
  this.active[id].active1 = true;
 }

 close(){
    this.active = false;
 }

I am encountering challenges when trying to assign the ngClass value from the active array. Since there are four modals, each has its own set of actives to determine their contents. How can I successfully implement

ngClass = "active[0].active1 : 'open'"
without running into errors? Furthermore, clicking a button triggers an error message stating 'Cannot set property 'active1' of undefined'. How can I resolve this issue?

Answer №1

To effectively handle an array of four booleans, there is no need for a nested dictionary structure; you can simply use:

boolArray: boolean[] = [false, false, false, false];

This approach will make your code more straightforward:

[ngClass] = "boolArray[0] ? 'active' : ''"

If you encounter the error

'Cannot set property 'boolArray1' of undefined'
, it indicates that the variable is not defined during rendering, and you should ensure proper tracking of variable states.

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

Running ng build --prod does not compile the source code

Upon running the following command: ng build --prod utilizing the following versions: node version: v6.11.0 @angular/cli: 1.0.0-rc.2 typescript: Version 2.4.2 encountered errors as shown below: ERROR in ./src/main.ts Module not found: Error: Can ...

Utilize Angular 9 to fetch data from an API using the Get method, map them to a class, and

Seeking to extract information from a test URL and convert the data into a list, I aim to exhibit them in an alert/Loop for testing purposes. The dummy API URL being used is: The returned data follows this structure: {"status":"success","data":[{"id":"1" ...

Angular Form Container

I am in the process of creating a wrapper for forms. Everything is functioning except for the validation aspect. The issue lies in the fact that my ngForm property does not include the controls from the ng-content. My objective is to have the ngSubmit Even ...

Upgrade of Angular 2 to rc 5 presents with unresolved peer dependencies

I am looking to update my angular version to rc5 in order to utilize NgModule. Following the directions provided by Angular 2. I have made changes to my package.json dependencies and then executed npm stall in the terminal: ... The results from the ter ...

Issue with TypeORM Many-to-Many relation returning incorrect data when using the "where" clause

I'm facing an issue with my database tables - User and Race. The relationship between them is set as Many to Many , where a Race can have multiple Users associated with it. My goal is to retrieve all the Races that a particular user is a member of. Ho ...

What is the most effective way to retrieve the width and height of an oversized image in Angular?

After attempting to retrieve the image width using the ngAfterViewInit method, a result of width = 0 is returned due to the large size of the image. Is there a way to accurately determine the image width without relying on a setTimeout() function? For re ...

The HTML component fails to acknowledge width settings

I seem to be having trouble identifying an issue or perhaps I am misunderstanding something (I am using daisyui + nx + tailwind css + angular). To simplify my problem, let's consider the following scenarios: In the first scenario, I have: <div cl ...

Is there a way to implement jquery (or other external libraries) within Typescript?

Currently, I am diving into Typescript to enhance my skills and knowledge. For a project that is being served with Flask and edited in VSCode, I am looking to convert the existing JavaScript code to Typescript. The main reason for this switch is to leverag ...

What are some methods for utilizing the "name" attribute within React components?

About My Coding Environment Utilizing TypeScript and ReactJS The Issue with Using name as an Attribute Encountering the following error: Type '{ name: string; "data-id": string; "data-type": string; }' is not assignable to ...

Comparison between a Typescript optional field and a field that has the potential to be undefined

Can you clarify the contrast between an optional field and a T | undefined field? export interface Example { property1: string | undefined property2?: string } ...

Is it possible to assign an interface to an object property in TypeScript?

I am currently working with an object that looks like this: export class Section{ singleLabel:string; pluralLabel:string; index:number; dataInterface:Interface; } My goal is to assign an interface to the dataInterface field, as I need to use the S ...

The RxJS race function comes to a standstill if neither stream completes

Consider the code snippet below: import { interval, race, Subject } from 'rxjs'; import { mapTo } from 'rxjs/operators'; const a$ = new Subject<number>(); const b$ = interval(1000).pipe(mapTo(1)); race([a$, b$]).subscribe(consol ...

Issue with vertical cell alignment in MUI x-data-grid persists following the latest update to version 7.2.0

After updating my MUI app to the latest npm packages version, specifically upgrading x-data-grid from 5.17.9 to 7.2.0, I encountered an issue. In my application, I utilize a grid where certain columns are populated using the renderCell property: const cel ...

Issue with Angular routing: Content from app.component is displaying in all components

Can anyone help me with the issue I'm having regarding showing app.component content on every component? Here is a snippet of my app.component code: I want to exclude the navbar and app-users from being displayed in other components, but unfortunatel ...

Websocket onmessage event triggered just one time

I have implemented a basic WebSocket client in an Angular 6 application. Everything seems to be working fine, except for the fact that both socket.onmessage and socket.addEventListener('message' are only triggered once. There are no errors in th ...

Angular - Evaluating the differences between the object model and the original model value within the view

To enable a button only when the values of the 'invoice' model differ from those of the initial model, 'initModel', I am trying to detect changes in the properties of the 'invoice' model. This comparison needs to happen in th ...

Utilizing handpicked information in Angular: A beginner's guide

Being new to Angular and programming in general, I am currently navigating through the intricacies of Angular and could use some guidance on utilizing selected data. For instance, I would like to use a personnel number view image here and send it to the b ...

Using React with Typescript: What is the best way to implement useMemo for managing a checkbox value?

I am currently developing a to-do list project using React and Typescript. At the moment, I have successfully implemented the functionality to add new to-do items via a form and delete them individually. Each item includes a checkbox with a boolean value. ...

`How can I sort information based on a chosen parameter?`

Is it possible to combine the two conditions into one within the function onSelectedReport()? Representing these conditions in HTML would result in: HTML: <div *ngFor="let report of reports"> <div *ngFor="let i of income"> <di ...

Ionic 4 Tabs with Smooth Scrolling

I recently started using Ionic 4 and I'm trying to create scrollable tabs in Ionic 4. However, when I include multiple tabs as shown in the code below, they become compressed and appear within the same viewing space. <ion-tab-bar slot="top"> ...