【问题标题】:Use multiple ngFor for same array对同一个数组使用多个 ngFor
【发布时间】:2019-01-23 16:01:12
【问题描述】:

Angular/Ionic noob 在这里。我在网上到处找(尤其是这个网站,因为它很有帮助),找不到有同样问题的人。我想要做的是在我的 ts 组件中有一个任务数组,然后在我的 html 模板中有四个不同的位置,我根据任务类型显示这些任务(使用 ngif 来确定它们应该结束的块中)。

我的 ts 组件中有一个 wizardTasks 任务数组,每个任务都是一个具有名称、类型、频率和“附加”属性的对象,其中包含有关任务的任何额外信息。

因此,从该数组中,我要显示的代码如下所示:

<ion-item-group>
  <ion-item *ngFor="let task of wizardTasks">
    <ion-label *ngIf="task.frequency==='oneTimeOnly' && task.type==='biological/physical'">{{task.name}}</ion-label>
    <ion-label *ngIf="task.frequency==='everyDay' && task.type==='biological/physical'">{{task.name}} every day</ion-label>
    <ion-label *ngIf="task.frequency==='daysOfWeek' && task.type==='biological/physical'">{{task.name}} every {{task.additional}}</ion-label>
    <ion-label *ngIf="task.frequency==='specificDate' && task.type==='biological/physical'">{{task.name}} on {{task.additional}}</ion-label>
  </ion-item>
</ion-item-group>

除了这些块中有四个 ngIf task.type 是四个组之一。

我遇到的问题是,当我这样做时,它会在所有四个地方为每个条目添加一个空格。因此,如果我有四个任务,每种类型一个,它会在适当的块中显示每个任务,但如果其他任务在该块中,它会在每个块中留出空格。

我希望这是有道理的。如果我需要添加任何其他内容,请告诉我,感谢您的帮助!

截图如果有帮助...

【问题讨论】:

  • 能否添加打印屏幕
  • 你能解释一下你说有四个这样的块是什么意思吗?我不确定您的描述中的原始代码是什么样的,但是如果我理解正确的话,听起来您可以通过使用&lt;ng-container&gt; 包装块来解决您所说的问题。您还可以使用[ngSwitch] 来增强您的某些模板。
  • 绝对!抱歉,我应该首先添加屏幕截图。因此,每个标题右上角的添加按钮会弹出一个模式来为该特定类别添加任务。然后每次返回主屏幕时都会更新任务。您可以看到它仍在每个标题下循环并向每个标题添加任务,但仅在它们实际上属于该类型时才显示它们(步骤 1 是生物,步骤 2 是情感等)。
  • 啊,如果任务类型不匹配,您只需要阻止显示&lt;ion-item&gt;?您可以为*ngFor 语句创建过滤器。组件代码:getWizardTasks(type: string): WizardTask[] {return this.wizardTasks.filter(task =&gt; task.type === type);}。模板属性:*ngFor="let task of getWizardTasks('biological/physical')".
  • @MikeHill 非常感谢!您可以将其添加为答案,我会标记它吗?那完全奏效了。我不知道你可以用 ngFor 做到这一点。

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


【解决方案1】:

根据原始问题的 cmets,您似乎正在为每个类别渲染所有 &lt;ion-item&gt; (wizardTask) 元素,无论它们是否适合该类别。您可以通过在使用 *ngFor 指令时过滤 wizardTasks 列表来解决此问题:

/* Component */
getWizardTasks(type: string): WizardTask[] {
    return this.wizardTasks.filter(task => task.type === type);
}

/* Template */
<ion-item-group>
    <ion-item *ngFor="let task of getWizardTasks('biological/physical')">
        <ion-label *ngIf="task.frequency==='oneTimeOnly'">{{task.name}}</ion-label>
        <ion-label *ngIf="task.frequency==='everyDay'">{{task.name}} every day</ion-label>
        <ion-label *ngIf="task.frequency==='daysOfWeek'">{{task.name}} every {{task.additional}}</ion-label>
        <ion-label *ngIf="task.frequency==='specificDate'">{{task.name}} on {{task.additional}}</ion-label>
    </ion-item>
</ion-item-group>

【讨论】:

    猜你喜欢
    • 2018-01-02
    • 2017-09-13
    • 2019-02-25
    • 1970-01-01
    • 2018-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多