How to ngSwitchCase in ngFor?
Asked Answered
F

1

6

From example in my code.

tabs: object = [
  { key: 'tab1', value: 'tab1' },
  { key: 'tab2', value: 'tab2' },
  { key: 'tab3', value: 'tab3' },
];
<div [ngSwitch]="my_tab">
  <div *ngFor="let tab of tabs" *ngSwitchCase="'{{ tab.key }}'">
    {{ tab.value }}
  </div>
</div>

I always get an error with this code. How to do this?

Fluctuate answered 11/1, 2018 at 12:41 Comment(1)
How to do what? What is the expected output? You can't put two structural directives on the same element - perhaps you want an ng-container somewhere but it's unclear what you're trying to achieve. Also note it's helpful to actually include the error.Centro
S
10

You can't put two structural directives on the same HTML tag. If you want your switch condition to be applied to each of the ngFor loop, you should write your HTML code like this:

<div [ngSwitch]="my_tab">
  <ng-container *ngFor="let tab of tabs">
    <div *ngSwitchCase="tab.key">
      {{ tab.value }}
    </div>
  </ng-container>
</div>

Also the ng-container allows to add a structural condition without interfering with the page's CSS style.

Sackman answered 11/1, 2018 at 12:47 Comment(6)
Doing it in this manner, the div with the ngFor still gets rendered. Is there any way to prevent the ngFor div from rendering?Krishnakrishnah
@Krishnakrishnah Maybe try to use an additional <ng-container> in place of the <div> used to loop with ngFor? (Downvoting other's answers in an attempt to promote your own answer is not very sportsmanship...)Sackman
Agreed that downvoting other's answer in an attempt to promote my own answer isn't very sportsmanship. However, I downvoted this answer because it doesn't really solve the issue (the div with the ngFor still gets rendered). I didn't downvote to promote my answer. My answer was provided quite a long time after I downvoted & commented.Krishnakrishnah
@Krishnakrishnah 7 minutes is not "quite a long time" according to me. Comment is posted at 17:04 yesterday and answer at 17:11 (just the time to write it). Also, downvote landed around the same span of time according to my reputation log.Sackman
You are right. Its my mistake. Very sorry for that. If you can modify your answer and I can remove the downvote, that'd be great :)Krishnakrishnah
@Krishnakrishnah I edited to try to avoid the empty div issue of the for loop. I couldn't test my answer since I don't have any Angular environment set up. If you can try this, I'd be curious to know if that solves the problem you mentioned. Thank you for raising that concern.Sackman

© 2022 - 2024 — McMap. All rights reserved.