2017-09-05 75 views
1

我有一个ngFor循环,我希望它只是通过阵列中的每个元素3迭代,就像我期待下面的代码工作:角4 - 有条件* ngFor显示每3元

for(let i=0; i<array.length; i=i+3)... 

我目前ngFor代码如下所示:

<md-card class="cardContainer" *ngFor="let viz of visualisationList; let i = index"> 
    <md-card-header> 
     <md-card-title>{{ viz['Title'] }}</md-card-title> 
     <md-card-subtitle>Datasets: {{ viz['Datasets'] }}</md-card-subtitle> 
    </md-card-header> 
</md-card> 

有一种简单的方式向ngFor环路内做到这一点?我可以使用ngInit()中的typescript预先过滤到3个数组中,或者我可以使用ngIf和模函数,但我希望我可以直接在ngFor循环中执行它。

回答

0

你可以到上一级移动ngFor到NG-容器和使用ngIf /对MD-卡上模,但我认为这是更好地准备你的数据在其到达视图之前,个人。

+0

是的,我知道。想知道是否可以直接在ngFor循环内完成所有操作。我知道你可以将if-then-else条件添加到ngFor循环中,但我还没有看到类似的东西。 – fila

3

最简单,在我看来,最彻底的方法是通过使用Array.filter和吸气像这样您的组件的逻辑里面的滤镜阵列:

public get filteredArray() { 
    return this.array.filter((value, index) => index % 3 === 0); 
} 

,并使用滤波阵列为您ngFor

注:如果阵列饰有作为输入可能undefined,你应该有一个空数组初始化或检查getter中,如果它使用filter方法之前不确定的。

+0

我觉得这种方式很简单,但我仍然希望在HTML中做到这一点。即使我不走HTML路径,我仍然想知道它是否可能。 – fila

+1

这可以通过'ngFor',index和'ngIf'的组合来实现,但是您应该尽可能保持模板不在模板之外。 – cyrix

0

你也许可以使用Pipe过滤出。但是,您仍然需要定义它使组件知道它。有一个内置的SlicePipe,这不是你想要的,但非常相似。在此基础上我想你可以使用:

@Pipe({name: 'thirdelement', pure: false}) 
export class ThirdElementPipe implements PipeTransform { 
    transform(value: any): any { 
    if (value == null) return value; 

    if (!this.supports(value)) { 
     throw invalidPipeArgumentError(ThirdElementPipe, value); 
    } 

    return value.filter((v, i) => (i % 3 == 0)); 
    } 

    private supports(obj: any): boolean { return typeof obj === 'string' || Array.isArray(obj); } 
} 

而且使用它像

<md-card class="cardContainer" *ngFor="let viz of visualisationList | thirdelement; let i = index"> 

甚至更​​通用的SkipPipe

@Pipe({name: 'skip', pure: false}) 
export class SkipPipeimplements PipeTransform { 
    transform(value: any, amount: number): any { 
    if (value == null) return value; 

    if (!this.supports(value)) { 
     throw invalidPipeArgumentError(SkipPipe, value); 
    } 

    return value.filter((v, i) => (i % amount == 0)); 
    } 

    private supports(obj: any): boolean { return typeof obj === 'string' || Array.isArray(obj); } 
} 

这应该是使用像

<md-card class="cardContainer" *ngFor="let viz of visualisationList | skip:3; let i = index"> 
+0

有趣的方法 - 我从来没有见过类似的东西。但是我从你的回答中猜测,在ngFor中没有Angular native可以让我做我想做的事情。我宁愿写一个函数返回一个具有正确元素的数组,而不是沿着这条路径 - 但感谢你的有趣的方法。 我应该在问题中指定我正在寻找的东西只需要在HTML中进行修改。 – fila

+0

我不知道纯粹的HTML方法,例如在''中用'* ngIf =“i%3 == 0”'进行过滤。然而,尽管管道方法需要一些JavaScript,你只需要在模块中定义一次管道。之后,您可以在模块的所有模板中使用它。这取决于你的用例可能是值得的。 – Matthias247

+0

喜欢这种新方法,并且仍然学到了一些新的东西,但不幸的是,这并不是我在寻找的问题。尽管如此,感谢新的知识。 – fila