angularionic-frameworkionic3angularjs-ng-switch

How to ngSwitchCase in ngFor?


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?


Solution

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