Search code examples
angularcomponentsangular2-directives

Conditional Buttons with ngSwitch also with ngFor from async piped array


I am having a logic error that I cannot seem to fix, but aside from the literal logic error, why doesn't Angular let me do this?

The reason for doing the conditional switch is I want drop downs for different models, Gender, etc. I have my gender drop down with drop.Name, however I just see [object object] in the drop down when it renders.

Incoming Code:

<drop-down [Content]="GenderTxt" [AriaLabel]="'Gender Select'" [Type]="'Gender'" [Options]="(MenuOptions | async)?.Genders"
            (Click)="SetGender($event)">
          </drop-down>

Error Message:

Can't have multiple template bindings on one element. Use only one attribute named 'template' or prefixed with * ("aria-labelledby="{{AriaLabel}}">
    <div [ngSwitch]="Type">
      <button *ngSwitchCase="Gender" [ERROR ->]*ngFor="let drop of Options" class="dropdown-item FakeClickable" (click)="Clicked(drop)">{{drop.Name}"): ng:///AppModule/DropDownComponent.html@6:37
Can't have multiple template bindings on one element. Use only one attribute named 'template' or prefixed with * ("-item FakeClickable" (click)="Clicked(drop)">{{drop.Name}}</button>
      <button *ngSwitchDefault [ERROR ->]*ngFor="let drop of Options" class="dropdown-item FakeClickable" (click)="Clicked(drop)">{{drop}}</bu"): ng:///AppModule/DropDownComponent.html@7:31

Code:

<div class="dropdown-menu" attr.aria-labelledby="{{AriaLabel}}" [ngSwitch]="Type">
    <button *ngSwitchCase="Gender" *ngFor="let drop of Options" class="dropdown-item FakeClickable" (click)="Clicked(drop)">{{drop.Name}}</button>
    <button *ngSwitchDefault *ngFor="let drop of Options" class="dropdown-item FakeClickable" (click)="Clicked(drop)">{{drop}}</button>
  </div>

Essentially is my problem that I need to move the switch case up to the outer level div, and then for each button create a new div?


Solution

  • You can't use two structural directives on the same element. Try this instead:

    <div class="dropdown-menu" attr.aria-labelledby="{{AriaLabel}}" [ngSwitch]="Type">
        <ng-container *ngSwitchCase="Gender">
            <button *ngFor="let drop of Options" class="dropdown-item FakeClickable" (click)="Clicked(drop)">{{drop.Name}}</button>
        </ng-container>
        <ng-container *ngSwitchDefault>
            <button *ngFor="let drop of Options" class="dropdown-item FakeClickable" (click)="Clicked(drop)">{{drop}}</button>
        </ng-container>
    </div>