Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Two structural directives on the same DOM element [duplicate]

While playing around with Angular 2, I've encountered a problem: apparently I can't put two structural directives (ngFor, ngIf) on the same DOM element.
In Angular 1 this used to work. For example:

<div ng-repeat="item in items" ng-if="$even">{{item}}</div>

When I try something similar with Angular 2:

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <div *ngFor="#item of items; #e = even" *ngIf="e">{{item}}</div>

    </div>
  `,
  directives: []
})
export class App {
  constructor() {
    this.items = ["a","b","c"]
  }
}

Nothing happens. Not even an error.

If I put the ngIf directive on a child element, it works:

<div *ngFor="#item of items; #e = even"><div *ngIf="e">{{item}}</div></div>

But the problem is I don't want to add a child element just for that. If, for example, it's a <tr> tag inside a table, then adding a div inside will make the DOM weird.

I know Angular 2 is still in beta, but I'm wondering if it's a bug, a feature, or maybe there's an undocumented way to achieve what I want.

like image 698
Yaron Schwimmer Avatar asked Jan 30 '16 10:01

Yaron Schwimmer


1 Answers

Two structural directives are not supported on one element. See also https://github.com/angular/angular/issues/4792

Instead nest them while using template syntax for the outer one and micro syntax for the inner one.

like image 187
Günter Zöchbauer Avatar answered Oct 13 '22 00:10

Günter Zöchbauer