1
votes

I have array of objects containing dates for ~ 2 years, price (the price is added dynamically later after the API calls) and validation that can be changed 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}
]

I want to display these dates dynamically as a calendar view so I created this div in my component.html:

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

calling this function:

  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 *ngIf does not work in the function: <div *ngIf="${calendarDate['price']}" class='fare'>${calendarDate['price']}</div> with error price is undefined (ignoring the *ngIf). How could I write this?

  2. When I click on div that will make this container available and start the function, it will call the function and therefore console.log("RENDER Calendar") multiple times. Is there any behaviour issue that I am not aware and causing calling the function many times?

  3. Because the prices are adding dynamically later, isn't there any better solution for similar problem? Especially when the array has almost ~600 dates to render (and listen for changes for ngIf price and date_is_valid.)

1
Why not do this in the HTML template, rather than building HTML within the code? - user184994
this is not REACT - in angular we have separation between html, js and css code (each type of code should be in separate file) - never mix it - here is some tutorial angular.io/guide/forms (at the bottom you will find files) - Kamil Kiełczewski

1 Answers

0
votes

A quick example for your question https://stackblitz.com/edit/angular-2u6pgj

Didn't implement the "month" block in your need because just want to show you how Angular deal with it, and the *ngIf works, that's enough.

You seem to misunderstand the way Angular handle Model and View, View is not dynamically "built" by Model, but is syncing data with Model. Please check its Architecture Ovreview