简体   繁体   English

在Angular 5中呈现* ngFor指令的索引值时遇到问题

[英]Facing issue while rendering index value of *ngFor directive in Angular 5

I am facing an issue while rendering index of *ngFor directive for a particular use case as follows. 如下所示,在为特定用例呈现* ngFor指令的索引时遇到一个问题。

Lets say we have an array of objects as 假设我们有一个对象数组

this.temp = [
  {name:'John',age:24,visibility:'visible',
  {name:'Kane',age:26,visibility:'hidden',
  {name:'Ross',age:28,visibility:'visible',
  {name:'Lui',age:21,visibility:'visible'
]

For rendering this in my app.component.html file I have html as follows 为了在我的app.component.html文件中呈现它,我有如下的html

<div *ngFor="let user of temp; let i = index">
 <div *ngIf="user.visibility === 'visible' ">
    <div>{{i+1}}</div>
    <div>{{user.name}}</div>
 </div>
</div>

So as per the above array example, it renders users 因此,按照上述数组示例,它呈现给用户

1.John
2.Ross
3.Lui

Now there is a button name 'Change visibility' against each user in my UI, where in it will toggle the visibility state of user from 'hidden' to 'visible' and viceversa. 现在,在我的UI中有一个针对每个用户的按钮名称“更改可见性”,在该按钮中,用户的可见性状态将从“隐藏”切换为“可见”,反之亦然。

So clicking on button mentioned against John, it will set its visibility as hidden but the UI rendered is 因此,单击针对John提到的按钮,它将设置其可见性为隐藏,但呈现的UI为

2.Ross
3.Lui

My expected output is 我的预期输出是

1.Ross
2.Lui

How to make the index render properly ? 如何使索引正确呈现?

The use case here is that I cannot modify/alter my this.temp array in terms of length.Basically I need the entire array with only visiblity property changed in it as per user actions. 这里的用例是我不能在长度方面修改/更改this.temp数组,基本上我需要整个数组,并且仅根据用户操作更改了visiblity属性。

Please help. 请帮忙。

you can filter array first: 您可以先过滤数组:

<div *ngFor="let user of temp.filter(us => us.visibility === 'visible'); let i = index">
 <div>
    <div>{{i+1}}</div>
    <div>{{user.name}}</div>
 </div>
</div>

like this way, you dont analize all array items too, more efficient and desired output. 像这样,您也不必对所有数组项进行分析,从而提高效率和所需输出。

Cheers! 干杯!

You can also achieve your required result by using Pipe like this 您也可以通过使用Pipe这样达到所需的结果

HTML component HTML组件

<div *ngFor="let user of temp | visiblefilter ; let i=index">
    <span>{{i+1}} {{user.name}}</span> <button name={{user.name}} (click)="onHide($event)">Hide</button>
</div>

PIPE

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'visiblefilter',
    pure: false
})
export class VisibleFilterPipe implements PipeTransform {
    transform(items: any[]): any {
        return items.filter(({visibility}) =>visibility=='visible');
    }
}

You can check here with working example stackblitz 您可以在这里查看工作示例stackblitz

use a custom trackby function : 使用自定义trackby函数:

*ngFor="let user of temp; let i = index; trackBy: customTB"

customTB(index, item) {
  return index + ' - ' item.name;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM