Search code examples
jsonangularconstructorhtml-renderingngoninit

Angular html component not rendering the local json data on loading the page


import { Store,STORES } from '../models/store';

export class StoreLocatorComponent implements OnInit { 
public Stores: any = [];
constructor() {  
   }

ngOnInit(): void {
      this.Stores = STORES ; 
      this.Stores.forEach(element => {
        console.log(element);
      });
  }

}

HTML Part

<ul>
      <li *ngFor="let store of Stores">
        {{store.name}}
      </li>
    </ul>

But this html page is not rendering the values inside Stores, whereas in logs i can see that the data in STORES object has been assigned to Stores, and ALSO the Stores data in html starts showing up when some activity is done on html page like click any random dummy button or something like that. This is probably related to how and when html page is rendered w.r.t the ngOnInit(), but can some one clarify how can i render the data of STORES on Initial Load of page WITHOUT having to click anything.


Solution

  • This is a symptom of the web page rendering before the binding. You can control the rendering.

    Put in a variable named show and set it to false.

    After this.stores has the data set show to true.

    On the ul tag in HTML add this.

    *ngIf='show'