1

I am trying to populate a dropdown in angular. I have a set of values that need to appear in the dropdown. Here is my code.

rolesArr: SelectItem[];

for (let i = 0; i < user.roles.length; i ++) {
    this.rolesArr = [
     { label: user.roles[i].name, value: i }
    ];
}

<div class="input-container">
     <label for="role">Role*</label>
     <p-dropdown [options]="rolesArr" formControlName="role" id="role" placeholder="Please select"></p-dropdown>
</div>

I am currently only seeing the last value in the data set.

This is my data set

{
  "roles": [
    {
      "id": 1,
      "name": "System Admin",
      "parent": "00000000-0000-0000-0000-000000000000"
    },
    {
      "id": 2,
      "name": "Internal Account Manager",
      "parent": "00000000-0000-0000-0000-000000000000"
    },
    {
      "id": 3,
      "name": "CAT Manager",
      "parent": "00000000-0000-0000-0000-000000000000"
    }
  ]
}
1
  • share the 'p-dropdown' component aswell Commented Mar 15, 2019 at 6:33

3 Answers 3

1

You are reassigning rolesArr every time when iterating user.roles.

  1. Assign an array to rolesArr.

  2. Call rolesArr.push() method.

rolesArr: SelectItem[] = [];

for (let i = 0; i < user.roles.length; i ++) {
    this.rolesArr.push({ label: user.roles[i].name, value: i });
}
Sign up to request clarification or add additional context in comments.

Comments

1

That's exactly what's expected with your current code. Be careful with your for loop. Every loop you re-assign the array to the current element. What you should do instead is use this.rolesArr.push({label:user.roles[i].name,value:i})

2 Comments

I am now getting ERROR TypeError: Cannot read property 'push' of undefined. I have added the data set in the question.
Add this line before the for loop " if(!this.rolesArr){ this.rolesArr = [] as SelectItem[] ;] "
1

You are not pushing into the array. You are setting the 0 value of the array. Try it with.

for (let i = 0; i < user.roles.length; i ++) {
    this.rolesArr.push(
     { label: user.roles[i].name, value: i }
    );
}

1 Comment

I am now getting ERROR TypeError: Cannot read property 'push' of undefined. I have added the data set in the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.