No response from NgClass after executing the function

In my NgClass function, I make use of an array that is populated in the ngOnInit lifecycle hook.

Within ngOnInit, the prepareRezerwation() function creates a variable called colorRezerwation:

    this.nodeService.getRezerwations(this.minMax).subscribe(rezerwations => { 
    this.prepareRezerwation(rezerwations);
    //   this.functionsService.showRezerwation(post, this.openingHours);
      // this.showSpinner = false;
    }, error => {
       console.log("Connection problem")
    }); 

In the HTML template, I apply the function setColor(1,i) using [ngClass]:

<ng-container matColumnDef="big">
    <th mat-header-cell *matHeaderCellDef class="xunk-calendar-cell"></th>
    <td mat-cell *matCellDef="let element; let i = index" [ngClass]="setColor(1,i)">Name</td>
</ng-container>

The setColor(1,i) function is defined as follows:

  setColor(colIndex, rowIndex){
    this.colorRezerwation.position.forEach(arrayItem => {
      if(arrayItem.column === colIndex && arrayItem.row === rowIndex){
        return {'reservation': true}
      } 
    });
  }

When I remove the forEach loop entirely, the function works correctly.

I appreciate all the assistance provided. Thank you!

Answer №1

You have been sending your class variable back to the forEach loop within the function instead of returning it to the setColor function.

setColor(colIndex, rowIndex){
    this.colorRezerwation.position.forEach(arrayItem => {
      if(arrayItem.column === colIndex && arrayItem.row === rowIndex){
   -->  return {'reservation': true} <-- this is not going back to setColor
      } 
    });
}

To fix this issue, you should declare and store the variable outside of the forEach loop and then return that:

setColor(colIndex, rowIndex){
    let classVar;
    this.colorRezerwation.position.forEach(arrayItem => {
      if(arrayItem.column === colIndex && arrayItem.row === rowIndex){
        classVar = {'reservation': true}
      } 
    });
    return classVar;
  }

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

Ways to categorize items retrieved from an HTTP request to the backend in Angular

When making a call to the backend using this http request: this.StudentEnrollment.getRecordsById(list.value.split(/[\r\n]+/)).subscribe(values => { this.studentObject = values; }); The studentObject is structured as shown below: { recor ...

Guide on how to execute jasmine tests coded in TypeScript for Node.js applications

I am eager to test my express application developed in TypeScript. I am utilizing jasmine for writing test cases, webpack for bundling TypeScript files to JavaScript, and karma as the test runner. Please locate the following files: // about.service.ts - ...

Setting up ESLint and Prettier for Accurate Error Detection in TypeScript and Next.js Development

As I work with TypeScript and Next.js, I decided to implement strict code formatting rules by adding the following configuration to my eslintrc.json file: "rules": { "prettier/prettier": "error" } However, when I ran npm ru ...

Typescript is failing to return nested types when attempting to return a nested object

My goal is for my function to return a nested type of Content, but it's not working even though the type that should be returned is known. Let's take a look at an example: type Content = { some: { extra: string; prop: number; ...

Nano frontend program

My current project consists of 5 different single-page applications (SPAs): 2 in Angular, 2 in React, and 1 in Vue.js. These SPAs are served by an integrated server that handles routing for each one. I am looking for a way to share data between these app ...

Explore the functionality of a TypeScript-created Vue component by testing it with Vue-test-utils

In my attempt to validate props with various data types in a Vue component (built using TypeScript), I utilized the Vue-test-utils package. Despite implementing expect().tobe(), there remains an untested line: DropDownList.vue <template> <v-sel ...

An unusual problem encountered while working with NextJS and NextAuth

In my NextJS authentication setup, I am using a custom token provider/service as outlined in this guide. The code structure is as follows: async function refreshAccessToken(authToken: AuthToken) { try { const tokenResponse = await AuthApi.refre ...

Is there a possibility of Typescript expressions `A` existing where the concept of truthiness is not the same as when applying `!!A`?

When working with JavaScript, it is important to note that almost all expressions have a "truthiness" value. This means that if you use an expression in a statement that expects a boolean, it will be evaluated as a boolean equivalent. For example: let a = ...

Discover the outcome of clicking on an object (mock tests)

I am just starting out with React and I'm unsure about when to use mocking. For instance, within the 'ListItem' component, there is a 'click me' button that reveals a dropdown for 'cameras'. Should I focus on testing what ...

Triggering a class in Angular when another class is activated through JavaScript

My goal is to apply the class "xyz" when the class "xy" is activated using ngClass. I am looking to achieve the following scenario: If the class "xyz" is present in the tag, then activate the class "xy" Using ngClass="'xyz', 'xy'" ...

Transform object properties into key-value objects using Typescript generics

When I receive a sorting object with a columnName and direction, I want to convert it into a key-value object for mongoose sorting. The return values are not matching up and I can't seem to figure out what I'm missing. These are the interfaces ...

What could be the reason for the Express function Router() returning a value of undefined?

Currently, I am working with TypeScript and Express to develop an API that adheres to the principles of Clean Architecture. To organize my application, I have structured each route in separate folders and then imported them all into an index.ts file where ...

Angular version 4 JSONP request callback

Currently, I am working on the migration of an Angular 1 application to Angular 4. One particular challenge I have encountered is a jsonp call to an endpoint over which I have no control. In the Angular 1 app, the following code snippet is being used: js ...

Tips for resetting a form after submission

Hey there, I'm currently working with Angular 7 and facing an issue with form submission. After submitting the form successfully, I want to reset it without triggering the required validation for input fields. Here's a snippet of my TypeScript co ...

The functionality of anchor links becomes disrupted once the APK is finalized in Ionic/Angular2 development

After testing my application using Ionic View, everything was functioning properly. The links, which were implemented using anchor tags with normal href attributes in the HTML, were working as expected. However, when I built the application and clicked on ...

Combining the Partial<CssStyleDeclaration> union type with a dictionary can lead to potential typing complications when the implicit any flag is

Using VueJS v-bind:style binding makes it possible to set CSS variables. I am attempting to create a union type that allows for the object passed to v-bind:style to retain typings for CssStyleDeclaration, while also being relaxed enough to accept an arbitr ...

Analyzing the object for interface compatibility

When I receive a query string in one of my REST endpoints using koa-router, each value of the query string object parameter is always a string: { count: "120", result: "true", text: "ok" } Within my codebase, I have an Interface that represents the ...

What is the best way to assign a value to a class variable within a method by referencing the 'this' keyword?

Is there a way to set the state of this Ionic react app when displaying the outcome of a reset service? I am facing challenges with using this.setState({resetSuccess}) within a method due to scope issues. (Details provided in comments) Here is the relevan ...

Angular reference numbers vs ngModel

When is it necessary to use [(ngModel)] on an input, and when can I simply use #reference? For instance: <div class="form-group"> <div class="input-group mb-2"> <input type="text" class="form-control" [(ngModel)]="newUser"> < ...

Accessing results from geocoder.geocode is restricted to local variables only

I need to extract longitude and latitude coordinates from google.maps.GeocodeResults in order to store them in an external Array<any>. Currently, I am able to display results[0], but encounter an OVER_QUERY_LIMIT error when attempting to add it to t ...