Encountered an issue with the 'ngForOf' directive in Angular 9 as it cannot be bound to 'tr' element since it is not recognized as a valid property

AngularDirectives are causing issues in my application.

After organizing my app into separate modules and adding

import { CommonModule } from '@angular/common';
in my child module, as well as
import { BrowserModule } from '@angular/platform-browser';
in my app.modules.ts file, I continue to encounter the following error.

Can't bind to 'ngForOf' since it isn't a recognized property of 'tr'.

I have searched for solutions online, but most suggestions simply mentioned to include CommonModule, which I have already done.

Below are the relevant files:

crud-list.component.html

<table class="table table-bordered table-striped">
  <thead>
    <tr>
      <th>Id</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor='let item of cruds'>
      <td>{{item.OrderNumber}}</td>
    </tr>
  </tbody>
</table>

crud-list.component.ts

import { Component, OnInit } from '@angular/core';
import { CrudRequestService } from '@modules/crud/crud-services/crud-request.service';

@Component({
  selector: 'app-crud-list',
  templateUrl: './crud-list.component.html',
  styleUrls: ['./crud-list.component.scss']
})
export class CrudListComponent {
  public cruds: Array<any>;

  constructor(private objService: CrudRequestService) {
    this.objService.get().subscribe(
      (oDataResult: any) => { this.cruds = oDataResult.value; },
      error => console.error(error)
    );
  }
}

crud.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';

import { CrudListComponent } from '@modules/crud/crud-list/crud-list.component';
import { CrudFormComponent } from '@modules/crud/crud-form/crud-form.component';
import { CrudComponent } from '@modules/crud/crud.component';

const routes: Routes = [
  {
    path: '', component: CrudComponent, children: [
      { path: '', component: CrudListComponent },
      { path: 'create', component: CrudFormComponent },
      { path: 'edit/:id', component: CrudFormComponent }
    ]
  },
];

@NgModule({
  imports: [CommonModule, RouterModule.forChild(routes)],
  declarations: [CrudComponent]
})

export class CrudModule { }

app.module.ts

/* all the necessary imports */

@NgModule({
  declarations: [
    AppComponent,
    ForbidenAccessComponent,
    PageNotFoundComponent,
    AppHeaderComponent,
    AppFooterComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    NgbModule,
    AppRoutingModule,
    CoreModule
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: JwtInterceptor,
      multi: true,
    },
    BreadcrumbsService,
    AccordionService,
    ModalService,
    RequestService,
    IdentityProviderService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

app-routing.module.ts

/* remaining imports */

const routes: Routes = [
  { path: 'home', canActivate: [AuthGuard], component: HomeComponent },
  { path: 'crud', canActivate: [AuthGuard], loadChildren: () => import('@modules/crud/crud.module').then(m => m.CrudModule)},
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  // Error status pages
  { path: '403', component: ForbidenAccessComponent },
  { path: '404', component: PageNotFoundComponent },
  { path: '**', redirectTo: '/404' }
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forRoot(routes)
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Answer №1

After testing your problem on StackBlitz, it appears that everything is working fine.

https://stackblitz.com/edit/angular-59827473

Ensure that you include your components in both the declarations module and in the Routes as well.

Answer №2

file-crud.module.ts

//exporting the crud component from the CRUD module
@NgModule({
  imports: [CommonModule, RouterModule.forChild(routes)],
  declarations: [CrudComponent],
  exports: [CrudComponent]
})

export class CRUDModule { }

Don't forget to include CommonModule in the imports array of your AppModule.

This should hopefully resolve any issues you're experiencing!

Answer №3

Identified the issue. While the app was functioning without any other problems except for the one mentioned, I discovered that when attempting to recreate the problem on StackBlitz, an error occurred. The error message indicated that I needed to include the CrudListComponent in my @NgModule declaration. Therefore, all I had to do was add the component, rebuild the application, and it resolved the issue.

crud.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';

import { CrudListComponent } from '@modules/crud/crud-list/crud-list.component';
import { CrudFormComponent } from '@modules/crud/crud-form/crud-form.component';
import { CrudComponent } from '@modules/crud/crud.component';

const routes: Routes = [
  {
    path: '', component: CrudComponent, children: [
      { path: '', component: CrudListComponent },
      { path: 'create', component: CrudFormComponent },
      { path: 'edit/:id', component: CrudFormComponent }
    ]
  },
];

@NgModule({
  declarations: [CrudComponent, CrudListComponent, CrudFormComponent],
  imports: [CommonModule, RouterModule.forChild(routes)]
})

export class CrudModule { }

Answer №4

After encountering the same issue with Ionic 5 & Angular 9, I spent hours searching for a solution. Ultimately, I pinpointed 3 main factors contributing to the problem.

1. Perform a clean rebuild (or reinstallation) of your project. For Ionic 5, you can use:

cordova clean; ionic cordova build android
(or rm -rf node_modules; npm install) in your project directory.

2. Often, this issue arises from CommonModule not being included in your component's module (or BrowserModule omitted from your app's module). For Ionic 5:

list.module.ts

import { CommonModule } from '@angular/common';
import { ListPage } from './list';
...

@NgModule({
  imports: [
    CommonModule,
    ...
  ],
  declarations: [ListPage]
})
export class ListModule {}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
...

@NgModule({
  exports: [
    FormsModule,
    ReactiveFormsModule
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    ...
  ],
  declarations: [AppComponent],
  providers: [
    StatusBar,
    ...
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

3. Depending on the version of Angular you are using, if Ivy is enabled (which is unlikely with current Ionic 5), you must include the ModalComponent in both the parent module's entryComponents and declarations. In this example, CalendarModule displays ListComponent as a modal. For Ionic 5:

calendar.module.ts

import { CommonModule } from '@angular/common';
...
import { CalendarPage } from './calendar';
import { ListPage } from "../../modals/list/list";

@NgModule({
  imports: [
    CommonModule,
    ...
  ],
  declarations: [CalendarPage, ListPage],
  entryComponents: [ListPage],
  providers: []
})
export class CalendarModule {}

P.S.: To enable or disable Ivy, adjust Angular compiler options in TypeScript config within

tsconfig.json

"angularCompilerOptions": {
    ...
    "enableIvy": false
 },
 

Answer №5

The problem arose while working with Angular 9. After updating from angular(9.0.1) to ~10.0.9, the issue has been resolved.

Answer №6

Can you explain the purpose of NgbModule in your app.module imports? I am familiar with @NgModule, but it seems that NgbModule does not need to be included in the imports section, only imported at the top.

Here are some suggestions: Make sure to unsubscribe from subscriptions in crud-list.component.ts and remember that the constructor should only be used for injection purposes. Try using ngOnInit instead ;)

export class CrudListComponent implements OnInit, OnDestroy {
 cruds: Array<any>
 dataSubscription: Subscription

 constructor(private objService: CrudRequestService) { }
 ngOnInit() {
  this.dataSubscription = 
  this.objService.get().subscribe(data => {
   this.cruds = data.value
  })
 }
 ngOnDestroy() {
    this.dataSubscription.unsubscribe()
  }
}

Answer №7

Dealing with a comparable problem not long ago, I discovered the solution. Simply include CrudListComponent in the declarations segment of CrudModule. Give it a try and see if it helps resolve your issue.

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

The Datepicker in MUI - React is unable to recognize the `renderInput` prop on a DOM element

I've been experimenting with the MUI version 5 DatePicker component. I followed the example provided in the MUI documentation's codesandbox demo. Here is how my component looks: const MonthPicker: FC = () => { const [value, setValue] = Rea ...

What is preventing me from adjusting the padding of the mat-button?

Trying to adjust the default padding of a mat-button, but encountering issues with changing the component's style. Any suggestions on how to subscribe to the default padding (16px)? I've attempted modifying CSS properties to set the padding of a ...

Guide to building a personalized validator for FormGroup

I'm working with a formGroup object that includes 6 fields. Out of these, 5 fields are required together - meaning at least one of them must have a value for the form to be considered valid. The specific field with the value does not matter as long as ...

Analyzing past UTC date times results in a peculiar shift in time zones

When I receive various times in UTC from a REST application, I encounter different results. Examples include 2999-01-30T23:00:00.000Z and 1699-12-30T23:00:00.000Z. To display these times on the front end, I use new Date(date) in JavaScript to convert the ...

Complete only the fields specified in the Interface definition

I have been developing a shopping cart service that implements a method to add a specified JSON object to a cart object. However, only the defined fields in the IProduct interface should be populated. JSON Object { "title": "Title 1", "descriptio ...

An unexpected token was discovered by Jest: export { default as v1 } when using uuid

While working on writing Jest tests for my React component in a Monorepo, I encountered an error while running the Jest test. ● Test suite failed to run Jest encountered an unexpected token... ...SyntaxError: Unexpected token 'export' ...

What are the steps involved in creating a definition file for npm?

Is there a recommended way to include a definition file (.d.ts) into an npm module as outlined in this guide? Specifically, how can I reference the node without using \\\ <reference /> due to restrictions? ...

Obtain an array containing only unique values from a combination of arrays

Is there a simple way or plugin that can help me combine values from multiple arrays into one new array without duplicates? var x = { "12": [3, 4], "13": [3], "14": [1, 4] }; The resulting array should only contain unique values: [1, 3, 4]; ...

What is the process for deploying an Angular application within an nginx container?

I need assistance in deploying my Angular app within a Docker Nginx environment. Below is my configuration: ./Dockerfile FROM node:12-alpine AS builder ENV NODE_ENV production WORKDIR /usr/src/app COPY ["package.json", "yarn.lock", "./"] RUN yarn install ...

Steps for creating an Observable<Object[]> using data from 2 different API requests

My goal is to retrieve an Observable<MyResult[]> by making 2 separate API calls to load the necessary data. The first call is to load MyItem. The second call is to load Gizmos[] for each item. In a previous question, I loaded the second API into t ...

Troubleshooting: Dealing with Cross-Origin Resource Sharing (CORS)

I'm facing an issue with my server.js files. One of them is located inside the backend folder, and when I run nodemon server.js on localhost:3000, everything runs smoothly. I start Angular by running ng serve inside the angular folder, and logging int ...

Transforming Time Stamp into Date Structure

I am trying to format a timestamp into a more readable date format. Currently, the timestamp I receive looks like this: 2018-10-10T05:00:00.000Z What I want to achieve is: 2018-10-10 05:00 PM This is how I am querying the document containing the times ...

Dealing with Errors on the Server-Side (.NET Core 5.0) Transmitting Error Messages to the Client (Angular 11) via the Network

I recently created a contact form that utilizes .NET Core 5.0 on the backend and Angular 11 on the client-side. This form allows users to input their information, which is then collected and sent to a designated email address. However, I am currently faci ...

What is the best way to target changing elements displayed by *ngIf?

Trying to access a dynamic element generated by ngIf in the code below has proven to be challenging. I attempted two different methods: Using ElementRef and querySelector Component template: `<div class="test" *ngIf="expr"> <a id="b ...

Updating input values in Angular 5 with the currency pipe

Currently, I am utilizing the currency pipe to convert input values in Angular 5. However, I have noticed that it only works after unfocusing the input box. I am seeking a solution where the value is masked as soon as it is entered, similar to the example ...

Strategies for enhancing efficiency in managing numerous service methods

I have developed a menu verification system that checks for product availability on each server. If a server does not have any products, the corresponding menu is hidden. My approach involves: Creating a service to check the products in each menu. Running ...

Heroku error: unable to locate tsc despite exhaustive troubleshooting efforts

I've been attempting to deploy a basic nodejs app on heroku, but I keep encountering the error mentioned above. Despite trying various solutions provided here, nothing seems to resolve the issue. Here's a summary of what I've attempted so fa ...

Typescript's date function offers a variety of useful features

Can anyone help me create a function that formats a date string for sorting in a table? The date is in the format: 08.04.2022 16.54 I need to convert this to a number or date format that can be sorted. I'm new to TypeScript and could use some guida ...

Just updated angular to version 15 and installed rxjs, but now the packages are reporting errors about missing rxjs dependencies

Feeling incredibly frustrated! After updating Angular and all packages to version 15, I am encountering an error when trying to serve the app. This same app worked perfectly fine on version 8, but now I'm facing this issue: Error: Failed to initialize ...

Swapping out .scss files in Angular with docker-compose has no impact

I recently developed a frontend application using Angular 8 and I wanted to implement different color themes for each environment (test/acc/prod). To achieve this, I created separate variables.scss files for each environment such as: variables.test.scss v ...