Error: 'ngForOf' is not recognized as a valid property of the 'tr' element

Since this afternoon, I've been facing a challenge that I can't seem to grasp.

The issue lies within a service I created; in this file, there is an object from which I aim to showcase the data in a loop.

An error message is displayed:

NG0303: Can't bind to 'ngForOf' since it isn't a known property of 'tr'.

img

Upon researching on Google, suggestions included adding imports: [BrowserModule] in app.module.ts. Yet, the problem remains unsolved...

I've attempted removing and re-adding the Portfolio component 10 times, but the issue persists.

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';



@NgModule({
  imports: [BrowserModule, FormsModule, AppRoutingModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent],
})
export class AppModule {}

portfolio.component.html

<div class="home-content container ">
   <h1 class="text-center pt-5 pb-3">Portfolio page</h1>
   <div class="row pt-3 container">
      <table class="table table-bordered">
         <thead class="thead-light">
            <tr class="text-center">
               <th scope="col">Name</th>
               <th scope="col">Firstname</th>
               <th scope="col">Address</th>
               <th scope="col">City</th>
               <th scope="col">Country</th>
            </tr>
         </thead>
         <tbody>
            <tr *ngFor="let portfolio of portfolios">
               <td scope="row" class="text-center"> {{ portfolio.portfolioName }} </td>
            </tr>
         </tbody>
      </table>
   </div>
</div>

portfolio.component.ts

import { Component, OnInit } from '@angular/core';
import { PortfolioService } from './portfolio.service';

@Component({
  selector: 'app-portfolio',
  templateUrl: './portfolio.component.html',
  styleUrls: ['./portfolio.component.css']
})
export class PortfolioComponent implements OnInit {

  portfolios : any;

  constructor(private servicePortfolio: PortfolioService) { }

  ngOnInit(): void {
    this.portfolios = this.servicePortfolio.portfolios;
    console.log("Test => " + JSON.stringify(this.portfolios));
  }

}

img

portfolio.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class PortfolioService {

  portfolios = [
    { 
      portfolioName: 'Lenglet',
      portfolioFirstName: 'Alison',
      portfolioAddress: '15, Fleurs',
      portfolioCity: '1300',
      portfolioCountry: 'Alost',
    },
    { 
      portfolioName: 'Rome',
      portfolioFirstName: 'Fredy',
      portfolioAddress: '15, Cerises',
      portfolioCity: '1700',
      portfolioCountry: 'Anvers',
    },
  ]

  constructor() { }
}

Data retrieval is not successful on the portfolio page.

img

To view the issue on Stackblitz and possibly find a solution, please visit here.

Your assistance in identifying and resolving this problem would be greatly appreciated.

Answer №1

Simple fix: Include the PortfolioComponent in your AdministrationModule like this

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AdministrationRoutingModule } from './administration-routing.module';
import { AdministrationComponent } from './administration.component';
import { PortfolioComponent } from './views/portfolio/portfolio.component';

@NgModule({
  imports: [CommonModule, AdministrationRoutingModule],
  declarations: [AdministrationComponent, PortfolioComponent],
})
export class AdministrationModule {} 

Explanation:

The component PortfolioComponent was missing from the declarations in the administration.module.ts. The rule is:

  • If a component is used within another component,
  • Both components must be in the same module OR the parent component's module must import the child component.

In this case, you likely do not need a separate module for PortfolioComponent since it is just a component.

You can test it out on stackBlitz

Answer №2

By declaring your portfolioComponent in the app.module.ts, it should function correctly. It appears that your portfolio.module.ts may not be properly imported.

Your routing seems to be flawed and not functioning correctly in multiple areas. I recommend troubleshooting your routing to ensure it is working as intended, and then double-checking the import of your module (whether lazy loaded or not).

You can test whether the module is imported by attempting to import BrowserModule in portfolio.module.ts and confirming there are no errors indicating it has already been imported.

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

Deactivate user input depending on a certain requirement

Greetings everyone, I am currently working with the following code snippet: <table class="details-table" *ngIf="peop && peopMetadata"> <tr *ngFor="let attribute of peopMetadata.Attributes"> <td class="details-property"&g ...

Vue's computed property utilizing typed variables

I am trying to create a computed array of type Todo[], but I keep encountering this specific error: No overload matches this call. Overload 1 of 2, '(getter: ComputedGetter<Todo[]>, debugOptions?: DebuggerOptions | undefined): ComputedRef<T ...

A new interface property type that is customized based on the type property that is passed in

My dilemma lies in a generic interface with a field depending on the passed type. I'm exploring the possibility of having another field that can accept any type from the passed type. For instance: interface sampleObject { name: fullName age: n ...

The presence of 'eventually' in the Chai Mocha test Promise Property is undefined

I'm having trouble with using Chai Promise test in a Docker environment. Here is a simple function: let funcPromise = (n) => { return new Promise((resolve, reject) =>{ if(n=="a") { resolve("success"); ...

Rxjs: handling arrays of observables by processing them in batches

I am facing a scenario where I have an array of observables. Let's say: const responses$: Observable<Response>[] = [ this.service.get(1), this.service.get(2), this.service.get(3), this.service.get(4) ]; My goal is to process ...

What is the reason behind the term "interpolation" for the double curly braces in Angular/

Even after over a year of experience with Angular/JS, I find myself struggling to truly grasp the concept of interpolation (for example, {{1+4}}). Can you explain the origin of this term in the context of Angular/JS and if it shares any similarities with ...

establish the data type for the key values when using Object.entries in TypeScript

Task Description: I have a set of different areas that need to undergo processing based on their type using the function areaProcessor. Specifically, only areas classified as 'toCreate' or 'toRemove' should be processed. type AreaType ...

Webpack 5: Updating the file path for TypeScript declaration files

My project structure includes a crucial src/ts folder: - dist/ - js/ - css/ - index.html - about.html - src/ - assets/ - fonts/ - images/ - sass/ - ts/ - services/ - service1.ts - ...

Tips for identifying and logging out a dormant user from the server side using Angular 2 Meteor

I'm currently diving into Angular 2 Meteor and working on a project that requires logging out the user when they close their browser window. I also need them to be redirected to the login page when they reopen the app. After searching online, I could ...

Learn the process of adjusting the Time Zone in Angular2-HighCharts!

I've been struggling for a few days now trying to adjust the UTC time in an area chart using Angular2-HighCharts. The backend API is returning timestamps which I then inject into the chart, but each time it's being converted to "human time" with ...

Tips for efficiently constructing a Docker container using nodejs and TypeScript

Struggling for the past couple of days to get the project running in production, but it keeps throwing different errors. The most recent one (hopefully the last!) is: > rimraf dist && tsc -p tsconfig.build.json tsc-watch/test/fixtures/failing.t ...

Transforming an array of elements into an object holding those elements

I really want to accomplish something similar to this: type Bar = { title: string; data: any; } const myBars: Bar[] = [ { title: "goodbye", data: 2, }, { title: "universe", data: "foo" } ]; funct ...

What is the best way to perform an AJAX request in Typescript with JSON data?

Currently, I am delving into the realm of AJAX and encountering some hurdles when attempting to execute an AJAX request with parameters. Specifically, I am facing difficulties in sending JSON data: My approach involves utilizing Typescript in tandem with ...

Ways to receive real-time notifications upon any modifications in my cloud firestore database?

I am currently in the process of developing a chat application using Angular and Firebase Cloud Firestore. My goal is to have a counter on the client side that updates whenever any document in the 'groups' collection is updated. Within my clien ...

Is there a way to ensure that the return type of a generic function is always optional in Typescript?

Is there a way to ensure the return type is always optional from a generic return type in functions? I specifically need the return types (data & error) to be optional at all times since one of them will always be undefined. TypeScript declarations i ...

The CORS policy has blocked the Vimeo URL from its origin, stating that the PATCH method is not permitted according to the Access-Control-Allow-Methods preflight response

Using Angular for web development. When uploading a video to Vimeo, it involves 3 steps: Create the video. Upload the video file. Verify the upload. The process of creating a video is successful, however, encountering an error during the vid ...

Are you facing a version issue when trying to install npm packages like [email protected] and [email protected]?

Previously, I encountered unmet dependencies in npm installation. To resolve this issue, I referred to this helpful discussion. However, now I am facing problems related to npm deprecated versions: [email protected] and [email protected] when try ...

One-Of-A-Kind Typescript Singleton Featuring the Execute Method

Is it feasible to create a singleton or regular instance that requires calling a specific method? For instance: logger.instance().setup({ logs: true }); OR new logger(); logger.setup({ logs: true }); If attempting to call the logger without chaining the ...

IntelliJ does not provide alerts for return type inconsistencies in TypeScript

During the development of our web application using react+typescript+spring boot with IntelliJ, everything seemed to be going smoothly until I came across an unexpected issue. Take a look at this code snippet example: export class TreeRefreshOutcome { } e ...

Encountered an error while trying to load config.ts file because of an issue

Trying to set up a new protractor project to conduct tests on an angular site. Node.js, typescript, protractor, and jasmine are all installed globally. After running webdriver-manager update and webdriver-manager start in the project folder, I proceed to b ...