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.