Home > Software design >  Want to access index of array in angular
Want to access index of array in angular

Time:12-14

I am getting array in this way, check attached image. enter image description here

Now I am trying to display edit icon as this below :

{
      header: 'Edit',
      field: 'id',
      view: (value: string, obj: any) => { return `<i class='material-icons' style='cursor: pointer;font-size: 20px;margin-left: 10px;'
       aria-hidden='false' aria-label='Example edit icon' userGuid=${obj}>edit</i>`; }
    }

In this userGuid I want to pass index of array, like 0, 1 etc..

So in obj I am getting full array but I am not sure how can I access that index and pass it in userGuid.

Any help.

CodePudding user response:

Can you try with cellRenderer property for rendering the edit button.

{
  header: 'Edit',
  field: 'id',
  cellRenderer: (params) => { return `<i class='material-icons' style='cursor: pointer;font-size: 20px;margin-left: 10px;'
   aria-hidden='false' aria-label='Example edit icon' userGuid=${params.rowIndex}>edit</i>`; }
}

CodePudding user response:

Let say the array from your picture has been saved to "const yourUserArray;".

There are 3 different way to access the your array:

Foreach:

  for(const user of yourUserArray){
        console.log(user); // Here is one user
        // Here you can add your if-condition to filter out your user
    }

For loop:

for(let i = 0, i > yourUserArray.length; i  ){
    console.log(yourUserArray[i]); // Here is one user
    // Here you can add your if-condition to filter out your user
}    

If you already know which user you want to call, just use brackets:

console.log(yourUserArray[5]); // Gets the 6th User from yourUserArray by index. 

Now you need the id of the user right?

You can call it like this:

console.log(yourUserArray[5].id); // Gives you the id of the 6th 

Do you also want to list all your users in the frontend?

If yes you can change your view into this:

<ng-container *ngFor="let user of yourUserArray">
<!-- Here some oder Information about the user? -->
<i class='material-icons' style='cursor: pointer;font-size: 20px;margin-left: 10px;'
       aria-hidden='false' aria-label='Example edit icon' userGuid={{user.id}}>edit</i>
</ng-container>

I hope this helps.

  • Related