Executing TypeScript functions that call multiple times to change the innerHTML of an Angular div

My array consists of objects with dates spanning approximately 2 years, prices (which are added dynamically post API calls), and changeable validations within the Angular app:

calendarArrayDates = [
  {"date": "2018-10-23", "price":"2313", "date_is_valid": true},
  {"date": "2018-10-24", "price":"2313", "date_is_valid": true},
  ...
  {"date": "2018-11-01", "price":"2313", "date_is_valid": false},
  ...
  {"date": "2019-02-01", "price":"2313", "date_is_valid": true}
]

To dynamically display these dates in a calendar view, I've created this div in my component.html:

<div [innerHTML]="renderHTMLCalendar()"></div>

This function is then called:

  renderHTMLCalendar(){
    console.log("RENDER Calendar");
    let container = "";
    for (var calendarDate of this.calendarArrayDates) {
      var date = calendarDate['date'];
      var mDate = moment(date)
      if (date === mDate.startOf('month').format(CALENDAR_DEFAULT_FORMAT)) {
        container = "<div class='month'>"
      }

      container += `<div>
                      <div class='day'>${calendarDate['date']}
                      <div *ngIf="${calendarDate['price']}" class='price'>${calendarDate['price']}</div>
                    </div>`;
      if (mDate === mDate.endOf('month')) {
        container += "</div>"
      }
    }
    return container;
  }
  1. The error occurs when using *ngIf in the function:

    <div *ngIf="${calendarDate['price']}" class='fare'>${calendarDate['price']}</div>
    due to price being undefined. How can this be resolved?

  2. Multiple instances of console.log("RENDER Calendar") indicate that the function is called multiple times upon clicking the respective div. Is there an underlying issue causing this behavior?

  3. Considering dynamic addition of prices at a later stage, is there a more efficient solution for rendering almost ~600 dates while accommodating changes in ngIf price and date_is_valid?

Answer №1

Just wanted to give you a quick example in response to your question. Check out this StackBlitz demo

I didn't include the "month" block as you requested, but I wanted to demonstrate how Angular handles it and show you that *ngIf works effectively.

It appears there may be some confusion about how Angular manages Model and View. The View doesn't dynamically build itself based on the Model; rather, it syncs data with the Model. For more information, please refer to the Architecture Overview

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

Unable to transmit props while employing Typescript in ReactJS

Attempting to pass props from components like AllProducts, MenProducts, etc. to the AddToCartButton component for reusability presents a challenge. When trying to pass props using: <AddToCartButton id={product.id} /> An error is encountered: Type & ...

Utilizing complex data with Angular 5 [Select+Option] - a comprehensive guide

I have a complex dataset stored in the app.component.ts file that looks like this: export class AppComponentimplements OnInit { tests = { 'name': 'Bob', 'grade': '5th', 'score' ...

Can you explain the purpose of the GenericType parameter in a TypeScript promise declaration for me?

I am curious about whether the generic type in Typescript's Promise<GenericType> definition indicates the type of the object passed to the then handler. As an example, consider the following code: const pr:Promise<Array<Number>> ...

Using .htaccess with Angular is specifically designed to function within a subfolder of

After deploying my app on a Debian 11 Apache server within the folder var/www/html (specifically in var/www/html/foo), I encountered issues with routing and hard refreshing, resulting in a 404 error whenever I attempted to refresh a page. The Angular app c ...

Tips for deleting a user from the UI prior to making changes to the database

Is there a way to remove a participant from the client side before updating the actual state when the submit button is clicked? Currently, I am working with react-hook-form and TanstackQuery. My process involves fetching data using Tanstack query, display ...

Mapping an array based on specific conditions

When using my photo gallery app, I faced a challenge in mapping an array of images based on the user-selected album name. The current setup works perfectly for the 'Cambodia' album where all images are correctly logged in the console after mappin ...

Exploring Angular's wild comparison capabilities for strings within HTML documents

I have a question that may seem basic, but I am curious if it is possible to use wildcards in *ngIf comparisons. Consider the following code snippet: <ng-container *ngIf="test == 'teststring'"> </ng-container> I am wonder ...

Coloring input fields in Angular Material 2

Changing Angular Material 2 Input Color <md-input-container > <input type="password" md-input placeholder="password"> </md-input-container> I am looking to change the color of the input field when it is clicked. Can anyone provide gu ...

What causes the typescript error in my code: The argument being passed is either a string, an array of FilterData, an array of numbers, or an array of Moments, which is not compatible with a parameter of type 'string'?

When writing my code, I have the need to utilize various types for different scenarios. Depending on the situation, the type may be a string, number[], FilterData[] (a custom type), or Moment[]. To address this requirement, I defined the type as: export ty ...

Tips for enabling custom object properties in Chrome DevTools

In my typescript class, I am utilizing a Proxy to intercept and dispatch on get and set operations. The functionality is working smoothly and I have successfully enabled auto-completion in vscode for these properties. However, when I switch to the chrome d ...

When comparing the values of two arrays with undefined property values

Struggling with sorting an array of arrays that works perfectly except when the property value is undefined. Take this example: posts array = {id: "1", content: "test", "likes":[{"user_id":"2","user_name":"test"}] }, {id: "2", content: "test", "likes": ...

Error in TypeScript in VSCode when using the React.forwardRef function in a functional component

We are developing our component library using JavaScript instead of TypeScript. In our project's jsconfig.json file, we have set checkJs: true. All components in our library are functional and not based on class components. Whenever a component needs ...

Troubleshooting a child process created by electron in Visual Studio Code

I am currently in the process of developing an electron application using typescript and webpack. I have encountered a specific debugging issue with vscode that I would like some assistance with: Context: The main process initiates a child process by call ...

Struggling to render the template inside a .vue file in a Vue.js + TypeScript project?

Is anyone familiar with setting up a Vue TS based project? I have encountered an issue where the template data is not being rendered in the browser's DOM. The project structure can be found in this repository: https://github.com/AndrewBogdanovTSS/typ ...

A specialized React hook designed for fetching data in a continuous loop

Been struggling with this issue for hours :( I have a hook called useCollection which is designed to provide data retrieved from my API and updated in real-time using a websocket. It works perfectly for real-time updates, but I want it to also update the ...

Is there a way to configure tsconfig so that it can properly recognize ".graphql" files and aliases when they are imported into components?

Currently, I have encountered an issue where including "graphql" files in my components is leading to TypeScript errors due to unrecognized import pathing. Despite the error, the functionality works as expected. import QUERY_GET_CATS from "@gql/GetCats.gra ...

Experimenting with throws using Jest

One of the functions I'm testing is shown below: export const createContext = async (context: any) => { const authContext = await AuthGQL(context) console.log(authContext) if(authContext.isAuth === false) throw 'UNAUTHORIZED' retu ...

Encountering difficulty importing a module from a different module within Nuxt

Within my Nuxt project directory, there exists a specific folder named modules which houses my customized modules. For this illustration, it includes the modules foo and bar. The inclusion of foo in the nuxt.config.js file appears as follows: // nuxt.confi ...

Creating a type definition for the createSelector function based on the useQuery result

Struggling to find the correct typings for the createSelector res parameter from redux-js, especially in TypeScript where there are no examples or explanations available. The only guidance is provided in JS. const selectFacts = React.useMemo(() => { ...

Can a map key value be converted into a param object?

I have a map containing key-value pairs as shown below: for (let controller of this.attributiFormArray.controls) { attributiAttivitaMap.set(controller.get('id').value, { value: controller.get('valoreDefault').value, mandatory ...