11

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.

Yaron Schwimmer
  • 5,327
  • 5
  • 36
  • 59

1 Answers1

7

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.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Is there any specific reason to not allowing this? – Ishan Fernando Mar 21 '22 at 17:39
  • This syntax is a short form that expands to a canonical form. It's not clear how to expand to the canonical form if there are more than one. I guess it boils down to HTML not providing the order of attributes (directives), but the order is significant, like *ngIf outside *ngFor or the other way around, is not the same. – Günter Zöchbauer Mar 22 '22 at 04:01