030
030

Reputation: 11679

Why is the `ngIf` not to be able to hide one of the two arrays?

Aim: to show a certain array if a certain value has been set

Steps to reproduce

Declare a two-dimensional array

arrays = [
      { id: 'a', name: ['a1', 'a2', 'a3', 'a4'] },
      { id: 'b', name: ['b1', 'b2', 'b3', 'b4'] }
];

In the App it is possible to click on two images. When the one is clicked el will be a and the other will result in b

Create two ngFor loops

<ul *ngFor="let arr of arrays">
  <a *ngIf="arr.id===el" (click)="aMethod(arr.name)">{{arr.name}}</a>
  <li *ngIf="arr.id===el" *ngFor="let arr2 of arr.name">
    <a (click)="aMethod(arr2)">{{arr2}}</a>
  </li>
</ul>

Expected outcome

a1
a2
a3
a4

or

b1
b2
b3
b4

Current outcome

a1,a2,a3,a4
a1
a2
a3
a4

b1
b2
b3
b4

or

a1
a2
a3
a4

b1,b2,b3,b4
b1
b2
b3
b4

Question

Why is the ngIf not to be able to hide one of the two arrays?

Upvotes: 1

Views: 44

Answers (2)

Bazinga
Bazinga

Reputation: 11204

You can't have multiple template bindings on one element. So you can't use both *ngIf and *ngFor on the same element. you can do this:

<ul *ngFor="let arr of arrays">
  <a *ngIf="arr.id === el" (click)="aMethod(arr.name)">{{arr.name}}</a>
  <li *ngIf="arr.id === el">
    <div *ngFor="let arr2 of arr.name">
      <a (click)="aMethod(arr2)">{{arr2}}</a>
    </div>
  </li>
</ul>

Now if the el is 'a' the results will be:

a1,a2,a3,a4
a1
a2
a3
a4

Because both *ngIf are true, but the 'b' will be hidden.

You can also use the template tag instead creating wrapper div:

<ul *ngFor="let arr of arrays">
  <a *ngIf="arr.id === el" (click)="aMethod(arr.name)">{{arr.name}}</a>
  <template [ngIf]="arr.id === el">
    <li *ngFor="let arr2 of arr.name">
      <a (click)="aMethod(arr2)">{{arr2}}</a>
    </li>
  </template>
 </ul>

And by the way you have a tag inside ul without li.

Upvotes: 2

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657228

What FunStuff said. You can work around using

<ng-container *ngIf="arr.id===el">
  <li *ngFor="let arr2 of arr.name">
</ng-container>

Upvotes: 1

Related Questions