Using Angular2's NgFor Directive in Components

I am faced with the challenge of converting a tree-like structure into a list by utilizing components and subcomponents in Angular 2.

var data = [
  {id:"1", 
   children: [
     {id:"2", 
      children: [
        {id: "3"},
        {id: "3"},
        {id: "3"},
        {id: "3"},
      ]},
      {id:"2", 
      children: [
        {id: "3"},
        {id: "3"},
        {id: "3"},
        {id: "3"},
      ]}
   ]}
]

My goal is to traverse this structure and generate an HTML list by using different components based on the depth of each loop iteration.

TypeScript

// ROOT
@Component({
    selector: 'root',
})

@View({
    templateUrl: '
    <childOne *ng-for="#data for list.children" [data]="data"></childOne>
    ',
    directives: [ChildOne, NgFor]
})

class Root{
    list:Array<Object>;
    constructor() {
       this.list = // request to backend
    }
}

// COMPONENT 1
@Component({
    selector: 'childOne',
    properties: ['data']
})

@View({
    templateUrl: '
    {{data.id}}
    <childTwo *ng-for="#childOneData for data.children" [data]="childOneData "></childTwo>
    ',
    directives: [ChildTwo, NgFor]
})

class ChildOne{
}

// COMPONENT 2
@Component({
    selector: 'childTwo',
    properties: ['data']
})

@View({
    templateUrl: '
    {{data.id}}
    <childThree *ng-for="#childTwoData for data.children" [data]="childTwoData"></childThree>
    ',
    directives: [ChildThree, NgFor]
})

class ChildOne{
    constructor() {
    }
}

// COMPONENT 3
@Component({
    selector: 'childThree',
    properties: ['data']
})

@View({
    templateUrl: '{{data.id}}',
})

class ChildThree{
    constructor() {
    }
}

HTML

<head>
  <body>
    <root></root>
  </body>
</head>

Issue

During execution, I encounter an error:

Can't bind to 'ngForFor' since it isn't a know property of the 'template' element and there are no matching directives with a corresponding property

This error specifically pertains to the *ng-for directive in the ChildTwo Component. Strangely, everything works perfectly fine once I remove the HTML tag.

Could there be any limitations or pitfalls when using *ng-for that I might have overlooked?

Thanks

Answer №1

Make sure to use of instead of for when using the ng-for directive:

<childTwo *ngFor="let childOneData of data.children" [data]="childOneData "></childTwo>

*ng-for updated to *ngFor

*#item transformed to let item

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

Handling ngRouterOutlet and component lifecycle - difficulties with displaying personalized templates

Overview I have developed a custom table component using Angular Material to display data and columns based on user configurations. While the component includes default templates for basic data types like strings and numbers, users are able to create thei ...

Tips for integrating Typescript Definition files with Visual Studio 2017

I have a challenge with my ASP.NET Core 2.0 application where I am attempting to incorporate TypeScript and jQuery. While TypeScript integration has been successful, I am facing issues with jQuery as it does not provide me with intellisense. Despite trying ...

Tips on refreshing a view in react as data updates

Currently, I am delving into learning a variety of subjects such as Typescript, Express, and my newfound interests in REACT and RXJS. To aid in my studies, I created a Quick-List on Github, but encountered a question... "How can the view in React be upda ...

Guide to dynamically setting the index element with ngFor in Angular

When working with NgFor in Angular, I am interested in dynamically handling attributes using an index. I have a collection of properties/interfaces that look like this: vehicle1_Name, vehicle2_Name, vehicle3_Name vehicle4_Name, totalVehCount To achieve t ...

The best way to access the value of a fulfilled Promise while debugging

I've been using this loopback application in my IntelliJ IDE. I set a breakpoint at the promise in calculator.controller.ts, where the code looks like this: @get('/multiply/{intA}/{intB}') async multiply( @param.path.integer('in ...

Ways to efficiently populate HTML elements with JSON data

I am working on grasping the concept of functional programming. My understanding so far is that it involves encapsulating everything into functions and passing them around. For instance, in my current example, I am attempting to fetch data from a RESTApi a ...

How come the index variable doesn't show the index in *ngFor loop in Angular 2?

When working with ng-repeat in Angular 1 to display the index, this code is used: <div ng-repeat="car in cars"> <ul> <li>Index: {{$index+1}}</li> <li>Car Name:{{car.name}}</li> </ul> </div> However, w ...

Insert placeholder text without access to the input field

Is it possible to activate a placeholder in a component that is outside of the current context? For example: <foreign-component [config]="someConfig" placeholder="somePlaceholder"></foreign-component> The <foreign-compo ...

Is it possible to eliminate auxiliary routes in Angular 4?

Recently, I came across an interesting scenario with two <router-outlet> tags, one with a name property. To test this, I set up the following router mapping: export const routing = [ {path:'', pathMatch:'full', component:E ...

Switching to Next.js

In my Next JS application, I have a div that dynamically displays the currency and price of a product when a user visits a product page. <div className="flex"> <Image src={EuroCurrency} alt="Euro Sign} /> <h1 className=" ...

When utilizing JavaScript syntax and performing API testing with Postman

Hello, I need some assistance from experts in connecting to Postman using the JavaScript code provided below. When running nodemon, the connection appears to be normal with no errors. Also, the GET request sent to Postman works fine. However, I am encounte ...

Reattempting a Promise in Typescript when encountering an error

I am currently working on a nodeJS application that utilizes the mssql driver to communicate with my SQL database. My goal is to have a unified function for retrieving a value from the database. However, in the scenario where the table does not exist upon ...

Issue encountered: Upon executing 'ng add @angular/fire', an error was detected in the node_modules/firebase/compat/index.d.ts file while attempting to launch the Angular application

Recently, I decided to integrate Firebase into my project, but encountered a persistent error after installing the firebase module 'ng add @angular/fire' and running it with 'ng serve': Error: node_modules/firebase/compat/index.d.ts:770 ...

What is the best method for replacing the current page in an Ionic app?

I am facing an issue with the following navigation flow: User lands on the Contacts page -> clicks on a button to navigate to the NewContact page using navController.push() method -> from there, user is directed to the ContactCreated page. How can I modi ...

Order of Execution

I am facing an issue with the order of execution while trying to retrieve values from my WebApi for input validation. It appears that the asynchronous nature of the get operation is causing this discrepancy in execution order. I believe the asynchronous b ...

Obtain the query response time/duration using react-query

Currently utilizing the useQuery function from react-query. I am interested in determining the duration between when the query was initiated and when it successfully completed. I have been unable to identify this information using the return type or para ...

I require assistance in displaying a dynamic, multi-level nested object in HTML using AngularJS

I have a complex dynamic object and I need to extract all keys in a nested ul li format using AngularJS. The object looks like this: [{"key":"campaign_1","values":[{"key":"Furniture","values":[{"key":"Gene Hale","values":[{}],"rowLevel":2},{"key":"Ruben A ...

Error encountered when providing valid data types as arguments in a React/Typescript function

I am facing an issue when passing a string variable to a function. To address this, I have created an interface called MyMessageProps where I declare the message as a string. Subsequently, the function MyMessage utilizes this interface to return with the ...

Live Reload isn't functioning

I recently came across some videos where the app automatically recompiled whenever any changes in the code were made. Typically, when ng serve is run, it should display a message like: Live reload server on ... However, for some reason this feature do ...

What is the best way to perform unit testing on a function component that includes React.useState() using jest and enzyme?

I'm working on a function component that utilizes React.useState() to handle the state of a drawer modal. My challenge lies in testing this function and its ability to modify state using jest enzyme, as I cannot access its state function due to it not ...