Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unlimited nested ngFor through child items

Tags:

c#

.net

angular

I found a couple of questions about nested ngFor loops in Angular2 but not what i'm looking for. I want to show categories in a list. My JSON looks like this:

{
    Categories: [{
        "Title": "Categorie A",
        "Children": [ 
            {
                "Title": "Sub Categorie A",
                "Children": []
            }
        ]
    },{
        "Title": "Categorie B",
        "Children": [ 
            {
                "Title": "Sub Categorie B",
                "Children": [{
                    "Title": "Sub Sub Categorie A",
                    "Children": []
                }]
            }
        ]
    }]
}

C# class looks like this:

public class Child
{
    public string Title { get; set; }
    public List<object> Children { get; set; }
}

public class Category
{
    public string Title { get; set; }
    public List<Child> Children { get; set; }
}

Now the trick is to get this in a ngFor loop without any restrictions on the depth of children.

like image 206
C. Molendijk Avatar asked Jan 31 '26 12:01

C. Molendijk


1 Answers

I think this would be pretty straightforward with a component that renders itself as child elements:

export interface Category {
  Title: string;
  Children: Category[];
}

@Component({
  selector: 'my-category',
  template: `
    <h2>{{ category.Title }}</h2>
    <ul *ngIf="category.Children.length > 0">
      <li *ngFor="let child of category.Children">
        <my-category [category]="child"></my-category>
      </li>
    </ul>
  `
})
export class MyCategoryComponent {
  @Input() category: Category;
}
like image 166
jonrsharpe Avatar answered Feb 02 '26 02:02

jonrsharpe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!