I want to do something like this:
<div *ngFor="let parent of parents">
<div *ngFor="let child of parent.children">
</div>
</div>
but I don't want that extra outer div. From what i've been able to find searching, in Angular 1 I could achieve this by doing this:
<template *ngFor="let parent of parents">
<div *ngFor="let child of parent.children">
</div>
</template>
This doesn't seem to work in Angular 2 though. What's the correct way to do this?
Angular 2 templating system gives us a syntax to express the dynamic part of our HTML. In Angular 2, a component needs to have a view. To define a view, you can define a template inline (using template) or in a separate file (using templateUrl).
ngFor adds a directive with the selector ngFor , let-xb makes the context of the template instantiation available within the template [ngForOf]="tempData" assigns tempData to the ngFor directive. That's quite common Angular2 template syntax.
*ngFor is a predefined directive in Angular. It accepts an array to iterate data over atemplate to replicate the template with different data. It's the same as the forEach() method in JavaScript, which also iterates over an array.
In *ngFor the * is a shorthand for using the new angular template syntax with a template tag, this is also called structural Directive.It is helpful to know that * is just a shorthand to explicitly defining the data bindings on a template tag. Follow this answer to receive notifications.
I think this should work for you:
<ng-template ngFor let-parent [ngForOf]="parents">
<div *ngFor="let child of parent.children">
</div>
</ng-template>
You can read more here:
https://angular.io/docs/ts/latest/guide/template-syntax.html#!#star-template
Also you can now use:
<ng-container *ngFor="let parent of parents">
<div *ngFor="let child of parent.children">
</div>
</ng-container>
The advantage here is that it has the same syntax as with a normal dom element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With