Display index of an Array - Angular 4+
Solution 1
Angular provides the index
variable in ngFor
so you can use it when iterating your array.
<div *ngFor='let tool of dropzone; let i = index'>
<label>{{dropzone.tool}}</label>
<label>{{ i }}</label>
<div>
There are other variables that the ngFor provides. You can read them from the official angular docs
Solution 2
Just as Bon Macalindong Pointed out correctly. Angular provides the index variable in ngFor so you can use it when iterating an array. But apart from declaring a variable with let in the *ngFor
statement, you can also use the as
keyword like so:
<div *ngFor='let tool of dropzone; index as i'>
<label>{{dropzone.tool}}</label>
<label>{{ i }}</label>
<div>
Related videos on Youtube
Comments
-
Gethma almost 2 years
I have a drag and drop function created. The dragged elements will be dropped to an array. The dragging tools are saved in one component. And there are 3 fields text, number and date will be dragged to this form. The inputs will be listened and then inserted to the dropzone array.I need to fetch the relevant index of the array and display. But i am unable to do it. Here are the code segments.
.html
<div *ngFor='let tool of dropzone'> <label>{{dropzone.tool}} </label> <div>
component.ts
dropzone = []; move(draggedTool, dropzone): void { dropzone.push(draggedTool); console.log(dropzone); }
output
(3) ["Text", "Number", "Date"] 0: "Text" 1: "Number" 2: "Date" length: 3 __proto__: Array(0)
How can i get the index of the dragged tool and display?
-
Sergey Rudenko over 5 yearscan you share more of your code specifically from draggable?
-
Bon Macalindong over 5 yearsDo you want to display it inside the template where you ngFor?
-
Gethma over 5 years@BonMacalindong yes
-
Bon Macalindong over 5 yearsDo this in your
*ngFor='let tool of dropzone; i = index'
wherei
will be the index. Then inside the ngFor you can use<span>{{ i }}</span>
-
Gethma over 5 years
compiler.js:1021 Uncaught Error: Template parse errors: Parser Error: Unexpected token = at column 25 in [let tool of dropzone; i = index] in ng:///PagesModule/FormComponent.html@8:9 (" </div>
It throws this error @BonMacalindong -
Bon Macalindong over 5 yearsSorry, you have to add
let
*ngFor='let tool of dropzone; let i = index'
-
Gethma over 5 years@BonMacalindong Yes. Great it works. Thanks!!
-