最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular Run *ngFor on particular Indexes Defined in Array - Stack Overflow

programmeradmin2浏览0评论

I am using a *ngFor loop but I only want the loop to run on particular indexes defined in an array (i.e. indexArray = [454,640]).

If I try this, and the indexArray has two or more elements, it does not work. But If the array has only one element (i.e. indexArray=[565]) it works.

<div *ngFor="let item of items; index as i">
  <table *ngIf="i == indexArray"> 

I am using a *ngFor loop but I only want the loop to run on particular indexes defined in an array (i.e. indexArray = [454,640]).

If I try this, and the indexArray has two or more elements, it does not work. But If the array has only one element (i.e. indexArray=[565]) it works.

<div *ngFor="let item of items; index as i">
  <table *ngIf="i == indexArray"> 
Share Improve this question asked Dec 3, 2020 at 1:56 Sanchit KumarSanchit Kumar 451 silver badge9 bronze badges 2
  • 1 So you only want to display the items at index 454 and 640 from the items array? Is that your goal? – Nick Parsons Commented Dec 3, 2020 at 2:00
  • Use <table *ngIf="indexArray.indexOf(i) >= 0">; In your case, you tried to pare with == this operator will convert the operand on the right hand to number(Number([565]) => 565 that why it equal to 565) – ttquang1063750 Commented Dec 3, 2020 at 2:01
Add a ment  | 

3 Answers 3

Reset to default 5

You can use .indexOf(i) and check whether it is in your indexArray variable.

<div *ngFor="let item of items; index as i">
  <table *ngIf="indexArray.indexOf(i)> -1"> 
  <!-- REST OF THE CODE -->

You can do the following:

<div *ngFor="let item of items; index as i">
  <table *ngIf="indexArray.includes(i)">
    enter code here...
  </table>
</div>

Here is a working example

create index array like this

public indexArray: array = [454,640];

do like below.

<div *ngFor="let item of items; index as i">
  <table *ngIf="indexArray.indexOf(i)> -1">
    enter code here...
  </table>
</div>

let me know if you have any doubt.

发布评论

评论列表(0)

  1. 暂无评论