【问题标题】:Is it possible to use ngIf to match two arrays and show correctly the parameters that don't match?是否可以使用 ngIf 来匹配两个数组并正确显示不匹配的参数?
【发布时间】:2021-08-16 01:03:20
【问题描述】:

我有一个项目需要过滤以显示它是否可用。我正在使用切换,因为它必须是动态的。问题是我有一个函数调用,它向我发送了一个标题数组,这些标题可以通过切换显示出来。

<ion-item *ngFor="let serVivo of seresVivos" id="items">
<div *ngFor="let available of availables">  
  <ng-template *ngIf="available === serVivo.title;then showBlock; else notShowBlock">
  </ng-template>
  <ng-template #showBlock>
    <ion-toggle  (ionChange)="change(serVivo.title, $event)" checked ></ion-toggle>
  </ng-template>
  <ng-template #notShowBlock>
    <ion-toggle  (ionChange)="change(serVivo.title, $event)"  ></ion-toggle>
  </ng-template>
</div>    
</ion-item>

因为它只能匹配一次,所以当标题匹配数组的一项时,它会正确显示切换。然而,由于不匹配的都是其余的,所以它创建了与数组可用的相同的项目。 Result with the actual code.The result only creating the true toggles

【问题讨论】:

    标签: angular ionic-framework ngfor angular-ng-if ng-template


    【解决方案1】:

    以下内容应通过 seresVivos 数组,显示 serVivo 的标题,如果 serVivo.title 在可用数组中,则显示切换为选中状态。

    <ion-item *ngFor="let serVivo of seresVivos" id="items"> 
        {{serVivo.title}}   
        <ion-toggle *ngIf="availables.includes(serVivo.title)" (ionChange)="change(serVivo.title, $event)" checked ></ion-toggle>
    </ion-item>
    

    但我认为,为了避免模板中的包含逻辑,更好的解决方案是处理 ts 文件中的数组,并向每个 seresVivo 添加类似 seresVivo.available 布尔字段的内容。

    【讨论】:

    • 该解决方案仅创建选中的切换,并且与数组长度一样多。我将尝试通过将选中的组件添加到 serVivo 对象来解决 ts 中的问题。谢谢
    • 在 ts seresVivos = seresVivos.map(seresVivo=&gt; ({...seresVivo, available:availables.includes(seresVivo.title)})); 和 *ngIf...else 模板中的逻辑如下
    【解决方案2】:

    如果您对已检查的属性设置条件会怎样!喜欢

    <ion-item *ngFor="let serVivo of seresVivos" id="items">
        <ion-toggle  (ionChange)="change(serVivo.title, $event)" [checked]="availables.indexOf(serVivo.title)>=0" ></ion-toggle>
    </ion-item>
    

    我认为这必须有效!试试这个! 如果没有,请告诉我!

    【讨论】:

    • 发生在我身上的和以前一样。那些被选中的工作完美,但是当它们没有被选中时,它会创建与可用数组参数一样多的切换
    猜你喜欢
    • 2017-07-19
    • 2018-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-28
    • 1970-01-01
    • 2016-11-26
    • 2021-05-19
    相关资源
    最近更新 更多