Filtering items by value inside ngFor without writing Pipes

六月ゝ 毕业季﹏ 提交于 2019-12-08 19:26:41

问题


I have the following Component:

class MyComponent {
  public mode = 'v';
  readonly modes = ['v', 'a', 'd'];
  ....
}

Now I want to use an ngFor to display buttons for all modes in modes except the current mode stored in mode. I have the following code:

<button *ngFor="let othermode of modes">
  {{ othermode }}
</button>

I always want two buttons to be displayed, containing the remaining 2 modes. I tried this:

<button *ngFor="let othermode of modes.filter(elem => elem !== this.mode)">
  {{ othermode }}
</button>

but it isn't working. All questions I saw required to write a custom pipe for this feature, but isn't there any simple way to filter an array of strings, using just the values ?


回答1:


You can use :

<ng-container *ngFor="let othermode of modes">
  <button *ngIf="othermode!=mode">
    {{ othermode }}
  </button>
</ng-container>



回答2:


Use a filter function for filter the data:

filterFunction(your_collection): any[] {  
    return your_collection.filter(i => i.field.value === filterKey);
}

and in the template:

*ngFor="let value of filterFunction(datasource)"

Or use a exist component. See the thread:

https://stackoverflow.com/a/50071762/4332063




回答3:


Use ng-template with ngIf, If you want to iterate the array with condition. Below is the sample code. you can find the working version here

<ng-template ngFor let-othermode [ngForOf]="modes">
<button *ngIf="othermode!=mode">
  {{ othermode }}
</button>
</ng-template>


来源:https://stackoverflow.com/questions/47406804/filtering-items-by-value-inside-ngfor-without-writing-pipes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!