带有 ngSwitch 的条件按钮也带有来自异步管道数组的 ngFor

Posted

技术标签:

【中文标题】带有 ngSwitch 的条件按钮也带有来自异步管道数组的 ngFor【英文标题】:Conditional Buttons with ngSwitch also with ngFor from async piped array 【发布时间】:2018-01-09 17:19:14 【问题描述】:

我遇到了一个似乎无法修复的逻辑错误,但除了字面逻辑错误之外,为什么 Angular 不让我这样做?

进行条件切换的原因是我想要不同模型、性别等的下拉列表。我的性别下拉列表带有 drop.Name,但是当它呈现时我只在下拉列表中看到 [object object]。

传入代码:

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

错误信息:

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

代码:

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

本质上是我的问题是我需要将开关盒向上移动到外层 div,然后为每个按钮创建一个新的 div?

【问题讨论】:

How to apply multiple template bindings on one element in angular2 RC4的可能重复 【参考方案1】:

您不能在同一个元素上使用两个结构指令。试试这个:

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

【讨论】:

我认为这是问题所在,但不知道如何重组以方便使用。 虽然我有你能回答我正在更新的这个问题的下一部分。 @BaileyMiller 你能创建描述问题第二部分的 plunker 吗? 我必须将很多代码添加到这个 plunker 中,我实际上是在传递一个包含一组性别模型的 Observable,当它显示在我的 *ngFor 中时,我只看到 @ 987654322@ @BaileyMiller 您只需要添加drop-dow 组件并传递模拟数据。

以上是关于带有 ngSwitch 的条件按钮也带有来自异步管道数组的 ngFor的主要内容,如果未能解决你的问题,请参考以下文章

NgSwitch在交换机上丢失了异步数据?

使用带有 viewpager 的异步任务时的竞争条件

禁用带有条件的按钮打字稿

如何在Heroku上托管带有Node后端的React应用程序?

如何根据带有闪亮元素的 R Markdown 文档中的条件禁用按钮?

如何使用条件关闭带有确定按钮的对话框[重复]