The Angular template loads and renders even before the dynamic data is fetched

I'm encountering a frustrating issue where the page loads before the data is retrieved. When I log the names in $(document).ready(), everything appears correct without any errors in the console. However, the displayed html remains empty and only shows the correct data upon refreshing the page.

Below is an excerpt from my component.ts file:

import {Component} from '@angular/core';
import {DataService} from '../../services/data.service';
import {ActivatedRoute, Router} from '@angular/router';
import * as $ from 'jquery/dist/jquery.min.js';
import 'jquery-ui/jquery-ui.min.js';

declare let jQuery: any;

@Component({
  selector: 'user-header',
  templateUrl: '../../templates/plan/header.html',
})
export class HeaderComponent {

  data;
  selectedCompany;
  selectedPlace;

  constructor(private dataService: DataService,
              private router: Router,
              private route: ActivatedRoute) {
    // Code to retrieve and select company/place data
    const self = this;
    $(document).ready(function () {
      console.log('selectedCompany', self.selectedCompany.name);
      console.log('selectedPlace', self.selectedPlace.name);
    });
  }

Here is a snippet from my template (html) file:

<li class="dropdown">
  <select [(ngModel)]="selectedCompany" (change)="selectCompany()" id="company-select">
    <option *ngFor="let company of data.companies" [ngValue]="company">
      {{ company?.name }}
    </option>
  </select>
</li>
<li class="dropdown">
  <select [(ngModel)]="selectedPlace" (change)="selectPlace()" id="place-select">
    <option *ngFor="let place of selectedCompany.foodHandlingPlaces" [ngValue]="place">
      {{ place?.name }}
    </option>
  </select>
</li>

If you have any suggestions on how to make the html wait for the data before rendering, please feel free to share!

Thank you for your help!

Answer №1

CEASE
UTILIZING
JQUERY
IN CONJUNCTION WITH ANGULAR

The message cannot be emphasized enough. JQuery is specifically designed for DOM manipulation, a task that should not be carried out within Angular.

If you need to ensure that your data loads properly, utilize conditions in your HTML template.

<li class="dropdown" *ngIf="selectedCompany && data.companies">
  <select [(ngModel)]="selectedCompany" (change)="selectCompany()" id="company-select">
    <option *ngFor="let company of data?.companies" [ngValue]="company">
      {{ company?.name }}
    </option>
  </select>
</li>
<li class="dropdown" *ngIf="selectedPlace && selectedCompany?.foodHandlingPlaces">
  <select [(ngModel)]="selectedPlace" (change)="selectPlace()" id="place-select">
    <option *ngFor="let place of selectedCompany.foodHandlingPlaces" [ngValue]="place">
      {{ place?.name }}
    </option>
  </select>
</li>

In the component file

import { Component, OnInit } from '@angular/core';
import { DataService } from '../../services/data.service';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'user-header',
  templateUrl: '../../templates/plan/header.html',
})
export class HeaderComponent implements OnInit {

  data;
  selectedCompany;
  selectedPlace;

  constructor(
    private dataService: DataService,
    private router: Router,
    private route: ActivatedRoute
  ) { }

  ngOnInit() {
    this.data = this.route.parent.snapshot.data;
    this.selectedCompany = this.data.companies[0];
    if (!this.dataService.selectedPlace.getValue()) {
      this.dataService.selectedPlace = this.selectedCompany.foodHandlingPlaces[0];
    }
    this.selectedPlace = this.selectedCompany.foodHandlingPlaces.filter(
      x => x.id === this.dataService.selectedPlace.getValue().id
    )[0];
    if (!this.selectedPlace) {
      this.selectedPlace = this.selectedCompany.foodHandlingPlaces[0];
    }
  }
}

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

Jasmine unit test fails to update component property with two-way binding when using Angular matInput

Using a matInput, I am updating a component property: <input matInput [(ngModel)]="componentProperty" /> <div>The value of componentProperty is: {{ componentProperty }}</div> While the input works as expected, with the displaye ...

Styling the pseudo element ::part() on an ion-modal can be customized based on certain conditions

Looking for a solution regarding an ion-modal with specific CSS settings? I previously had the following CSS: ion-modal::part(content) { width: 300px; height: 480px; } Now, I need to adjust the height based on conditions: if A, the height should be lo ...

The outcome of data binding is the creation of a connected data object

I am attempting to link the rows' data to my view. Here is the backend code I am using: [Route("GetCarCount")] [HttpGet] public async Task<long> Count() { return await _context.Cars.CountAsync(); } ...

Asynchronous problem when using Firebase calls within an Angular ForEach loop

Here's the code snippet I'm working with: getTotalBookListCost(bookList:string[]):number { let cost=0; bookList.forEach(el=>{ this.store.doc("Books/"+el).get().subscribe(data=>{ let temp=<Book>data.da ...

Can TypeScript types be created using multiple comma-separated strings?

Is it feasible to define a custom type in TypeScript like Type LayoutType = "Left" | "Right" | "Top" | "Bottom" | "VCenter", that would combine values such as "Left,VCenter"? Or do I need to create a string literal for every possible combination? ...

In Next.js, the Typescript compiler does not halt when an error occurs

I am looking to incorporate Next.js with TypeScript into my project. I followed the official method of adding TypeScript to Next.js using npx create-next-app --typescript. Everything seemed fine, but when a TypeScript error occurs (e.g. const st: string = ...

ag-grid Top-Endless Scrolling

Seeking knowledge here, it's a general question without specific code example but eager for an answer :) Currently exploring the combination of ag-grid with Angular and in need of implementing infinite scroll functionality where data is requested whe ...

Connect the names of the sheets with the data in the tables

I have a simple question: I want to connect specific sheet names in my workbook with a table that contains a range of dates. The sheet names should be something like "blablabla" + Table@1. Although I have attempted to design a solution, it doesn't se ...

The plugin "proposal-numeric-separator" was not found. Please make sure that there is a corresponding entry for it in the ./available-plugins.js file

{ "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "myProjects", "projects": { "uniqueApp": { "projectType": "web-app", "schematics": {}, "root": "", "sourceRoot": "src", ...

Is there a way for me to retrieve the bodyHeight attribute of ag-grid using public variables or data?

Working on a project using ag-grid community react. The main feature is a scrollable section filled with data, which can range from one piece to millions of pieces. I'm also incorporating a footer component for the grid that needs to adjust its height ...

Unable to assign unique identifiers to elements within a user interface framework

I am having difficulty assigning an id to components. Scenario 1: - Trying to assign an id to an HTML component. <h1 id="demo-h1">Demo Heading</h1> Assigning id to HTML component Scenario 2: - Attempting to assign an id to a componen ...

Why can't Angular iterate through objects using ngFor in Typescript?

Here's what I currently have: public posts: QueryRef<PostsInterface>; this.posts = this._postService.get(); //in ngOnInit In my HTML file, it looks like this: <mat-card *ngFor="let post of posts | async"> This allows me to display eac ...

Unable to assign a value to the HTMLInputElement's property: The input field can only be set to a filename or an empty string programmatically

When attempting to upload an image, I encountered the error message listed in the question title: This is my template <input type="file" formControlName="avatar" accept=".jpg, .jpeg .svg" #fileInput (change)="uploa ...

invoking an API within a map function and utilizing the response

vm.owners = parents.children.map(function(e) { getparentById(e.Id) .then(function(getresponse) { var parentLink = '<a href="/#/parent/onboard/' + e.Id + '" target="_blank">' + e.Number + "-&qu ...

Creating unique random shapes within a larger shape on a canvas, as shown in the image

I have a parent rectangle and would like to add up to 10 or fewer rectangles on the right-hand side corner of the parent rectangle, as shown in the image below: I attempted to write code to achieve this, but the alignment is off-center from the parent rec ...

Can you please explain the process of implementing server-side rendering with React?

During my work, I utilized Node's express for sever side rendering with React. However, an unexpected error occurred as shown below. ^ SyntaxError: Unexpected token '<' This particular error popped up unexpectedly. I reached ou ...

Is it possible to adjust the color of the iOS status bar using NativeScript, Angular 2, and TypeScript?

I recently came across this npm package called NativeScript Status Bar, available at the following link: https://www.npmjs.com/package/nativescript-statusbar However, I'm facing an issue because I cannot use a Page element as I am working with Angul ...

Angular form: Choose an option by selecting it and clicking on a button

I need help with my Angular form. I want to allow users to select a value when they click on a button. How can I achieve this? page.html <div *ngFor="let product of products; index as i"> <button (click)="chooseProduct(i)">{{product.name} ...

React: The Material-UI autocomplete input, controlled with the React Hook Form `<controller>` component, experiences issues when the `multiple` prop is set to `true`

Currently facing challenges with managing an autocomplete MUI component using the <controller> component in react-hook-form. Take a look at the code snippet below: <Controller control={control} name="rooms" render={({ field }) =&g ...

Mastering Light and Camera Selection in Three.js

Question, In the editor found at this link, you can click on a light or camera to select it. I am familiar with using raycaster.intersectObjects(objects) to select meshes, but how can I achieve the same result for lights and cameras which do not have mesh ...