Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of <template *ngFor in Angular 2?

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?

like image 554
user3715648 Avatar asked Sep 02 '16 20:09

user3715648


People also ask

What is a template in angular 2?

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).

Can we use ngFor in ng-template?

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.

What is * ngFor in Angular?

*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.

What does the * mean in ngFor?

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.


1 Answers

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.

like image 51
Filip Lauc Avatar answered Oct 14 '22 07:10

Filip Lauc