When fresh components are not refreshing after data retrieval, they do update if they are existing components

I've encountered an issue while working on a project where the ngFor directive doesn't re-render once it receives data. I conducted a test by copying the exact same code into 2 different components. Surprisingly, it works in the old component but not in the new ones. I've tried this with several new components and none of them seem to work. The situation is so peculiar that I'm unsure if I'll be able to replicate it.

(I have experimented with using trackBy, async, changeDetection, Observables, Promises by adding the logic to the OnInit block)

Both components are part of a module called AdmisionesModule

@NgModule({
  declarations: [
    newComponent,
    oldComponent,
    ...
  ],
  imports: [
    AdmisionesRoutingModule
    ...
  ],

This is the structure of AdmisionesRoutingModule

const routes: Routes = [
  { path: '', component: containBothComponent },
  { path: 'comprobantePago/:referencia', component: containBothComponent },
  { path: 'error/:codigo', component: containBothComponent },
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class AdmisionesRoutingModule {}

Then, AdmisionesModule is being referenced in my app-routing.module.ts

const routes: Routes = [
  { path: '', redirectTo: '/usuario/iniciar-sesion', pathMatch: 'full' },
  { path: 'usuario', loadChildren: () => import('@login/login.module').then(mod => mod.LoginModule) },
  { path: 'admisiones', canActivate: [SecurityGuard], loadChildren: () => import('@admisiones/admisiones.module').then(mod => mod.AdmisionesModule)},
];

The code utilizing ngFor is quite simple

newComponent.ts/newComponent.ts

options: any[];

constructor(public myServices: MyService) {
this.myServices.askService().subscribe({
      next(values: any[]) {
        this.options = values;
      },
      error(err) {
        console.error(err);
      },
    });
}

newComponent.html/newComponent.html

<p *ngFor="let option of options">{{option.economic_sector_desc}}</p>

Details about the project and environment:
Angular CLI: 16.1.8
Node: 18.15.0
Package Manager: npm 9.7.2
Angular: 16.2.7

@angular-devkit/architect       0.1602.4

@angular-devkit/build-angular   16.2.4

@angular-devkit/core            16.2.4

@angular-devkit/schematics      16.1.8

@angular/cdk                    16.2.6

@angular/cli                    16.1.8

@angular/material               16.2.6

@schematics/angular             16.1.8

rxjs                            7.8.1

typescript                      5.1.6

zone.js                         0.13.3

If there are any details missing, please inform me.

(I have experimented with using trackBy, async, changeDetection, Observables, Promises by adding the logic to the OnInit block)

In addition, when testing the code on various components, the original ones function correctly while the one I added does not. My goal is for the component to render automatically when the ngFor directive receives new data, and I aim to understand why it's not functioning in order to prevent future issues.

Answer №1

Make sure you have included CommonModule in your imports - this could be the cause of the issue.

For more information, refer to the [ngFor][1] documentation.

The best practice for rendering data is to use asyncPipe.

Declare an observable in your component:

public options$: Observable<any[]> = this.myServices.askService();

Update your template as follows:

<ng-container *ngIf="option$ | async as optionsList">
  <div *ngFor="let option of optionsList">
    {{ option }}
  </div>
</ng-container>

Thank you! [1]:

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

Retrieving data from a form input that utilizes reactive checkboxes

Hey there, I am currently working on implementing a Reactive Form and facing an issue with fetching values from checkboxes. It seems that only the value of the first checkbox selected is being recognized while the others are not. Below is the snippet of my ...

Is the type safety of Typescript Discriminated Unions failing on nested objects?

I am working on a project using Typescript 4 where I am trying to create an object with discriminated unions. However, it seems that the type safety is not functioning as expected. export enum StageType { PULL = 'pull', FILTER = 'fil ...

What is the rationale behind TypeScript occasionally labeling an impossible intersection as 'never'?

There are instances where TypeScript will determine that two types, when intersected, do not have any compatible values. This situation of an empty intersection is known as never, indicating that it is impossible to provide a value that satisfies both type ...

Refine the list by filtering out multiple search criteria using a nested array

I am working with an Array of objects that looks like this: data = [{ cities: [ {name: 'TATUÍ', federatedUnit: 'SP'}, {name: 'BOITUVA', federatedUnit: 'SP'}, {name: 'PORTO FELIZ', federatedUnit: ...

Instant reaction upon subscription

Presenting my unique service: @Injectable({ providedIn: 'root' }) export class DataService { @Output() data: EventEmitter<number> = new EventEmitter(); constructor() { setInterval(() => { this.data.emit(Math.random()); ...

Send out several async requests at once, but only pause and wait for the first

I am seeking advice on how to handle asynchronous requests for data from various sources on the web. My goal is to retrieve information from different sources, but I am only interested in getting the required data once without caring about the other source ...

PrimeNG Angular Editor: A Guide to Using Multiple Instances

Hello there! I am currently utilizing the PrimeNG editor within an Angular application and have multiple instances of the PrimeNg editors. File: x.component.html <p-editor [modules]="quillConfiguration" formControlName="questionName" ...

Transforming an array of JavaScript objects into arrays of key-value pairs based on a specific property with ES6 syntax

Consider an array of objects like this: myArray = [ {name: 'First', parent: 1, delta: 2}, {name: 'Second', parent: 1, delta: 1}, {name: 'Third', parent: 2, delta: 1} ]; The goal is to transform this array into an objec ...

Substitute a specific text within an array of strings using Angular 2

Currently, I am working with a string array that includes elements such as age, gender, and nationality. Specifically, I am interested in replacing the element "age" with "agexxxx". Do you know of any methods to accomplish this within an Angular framewor ...

Angular project seems to be stuck in a continuous cycle of

Currently, my application consists of spring boot as the backend and Angular as the front end. However, when I try to access the application through localhost:4200, the page continuously refreshes every few seconds. This issue did not occur previously, so ...

What is the best way to merge two subscriptions in Angular?

Is it possible to merge the subscriptions for this.controls.attendanceDate and this.controls.type? I require simultaneous access to both in order to execute both this.isAttendanceDateOnOrAfterStartDate() and this.isAttendanceDuplicate() within the if sta ...

Using Nest JS to create two instances of a single provider

While running a test suite, I noticed that there are two instances of the same provider alive - one for the implementation and another for the real implementation. I reached this conclusion because when I tried to replace a method with jest.fn call in my ...

Angular 7: Finding the variance between array elements

How can I subtract the values from the first 3 rows of the table? The formula is TVA Collectée - TVA Déductible - TVA Déductible/immo If the result is positive, it should be displayed in the box labeled TVA à Payer. If it's negative, it should g ...

Keys preset in TypeScript using keyof

I need a set of predefined keys, but users should not be restricted to only using those keys. type B = { a: string; b: number; } type T = keyof B | string; function someFunc(key: T) {} someFunc(); // key type is `T` In the scenario above, I am lo ...

Unlocking an alternative Firestore database in AngularFire

I am encountering an issue while trying to access a different firestore database within my gcloud project. I have successfully accessed the default database, but I am unable to access the 'development' database and cannot find any relevant docume ...

What is the best method for distributing an Angular service from a library created using ng generate library?

I'm currently facing a challenge in sharing a service from the npm package that I created using ng g library with my Angular hosting application. While I have experience in linking components and directives, I'm a bit lost when it comes to servic ...

I am attempting to update the URL of an iframe dynamically, but I am encountering an issue: the Error message stating that an Unsafe value is being

Currently, I am attempting to dynamically alter the src of an iframe using Angular 2. Here is what I have tried: HTML <iframe class="controls" width="580" height="780" src="{{controllerSrc}}" frameborder="0" allowfullscreen></iframe> COMPONE ...

Nest is having trouble resolving dependencies for this service

Can multiple MongoDB models be injected into one resolver and used? I attempted to accomplish this by first adding the import of SectionSchema and SectionsService to the PostsModule: @Module({ imports: [MongooseModule.forFeature([{name: 'Post&apos ...

Troubleshooting issues in a lerna-typescript project using VSCode

Currently, I'm in the process of constructing a monorepo using lerna and typescript. To get started, I'm utilizing this repository as a foundation: https://github.com/Izhaki/mono.ts My main objective is to debug the code within Visual Studio Cod ...

Asynchronous Requests with Axios - Maintaining Performance Levels

Currently, I am facing an issue while sending multiple GET requests to an API using promises. It seems that making 200 requests in a short time span exceeds the maximum number of allowed connections. I have been using axios for this purpose: const member ...