0

I am trying to display the id of the selected objects of the employee array which is a dropdown.

export const employees = [
 {index:1,'name':"Josh",'id':"102A"},
 {index:2,'name':"Sam",'id':"598A"},
 {index:3,'name':"Cal",'id':"345A"},
 {index:4,'name':"Elise",'id':"66A"}
];

<app-dropdown
  [(ngModel)]="project.employees"
  [items]="employeesDropdownItems"
  [multiselect]="true"
  (ngModelChange)="onEmployeeChanged()"
  placeholder="Select employee"
>
</app-dropdown>

{{project.employees.id}} doesn't seem to work. Is there any other way to achieve this?

Thanks!

9
  • employees is an array and you are trying to get the id of a specific employees an array withouth using index ! project.employees.id Commented Dec 27, 2021 at 16:19
  • What does App-dropdown components does? Commented Dec 27, 2021 at 16:20
  • App-dropdown creates a multi-select dropdown element. @VimalPatel Commented Dec 27, 2021 at 17:26
  • @Hamza, Could you please elaborate? Commented Dec 27, 2021 at 17:30
  • How do you know what items are selected? Do you have any array to store it? Commented Dec 27, 2021 at 17:34

1 Answer 1

2

You are trying to print the id of the employees using {{project.employees.id}}. But the problem is that employees array has elements of type { index: number, name: string, id: string }. To retrieve any element in this array, you need to know its index. If you are looking to print the first object, you need to provide the starting index, like project.employees[0]. If you just wish to print the id of the first object, you use project.employees[0].id. Similarly, if you wish to print the id of all the elements in the array, you need to loop over the entire array and print its id.

const employees = [
 {index:1,'name':"Josh",'id':"102A"},
 {index:2,'name':"Sam",'id':"598A"},
 {index:3,'name':"Cal",'id':"345A"},
 {index:4,'name':"Elise",'id':"66A"}
];


let toPrint = [];
employees.forEach(employee => toPrint.push(employee.id))
console.log(toPrint)

Or, a more simplified one in JavaScript is map:

const employees = [
 {index:1,'name':"Josh",'id':"102A"},
 {index:2,'name':"Sam",'id':"598A"},
 {index:3,'name':"Cal",'id':"345A"},
 {index:4,'name':"Elise",'id':"66A"}
];

let toPrint = employees.map(employee => employee.id)
console.log(toPrint)

In your case, you can write the above logic in your onEmployeeChanged() function like:

public toPrint: any;
onEmployeeChanged(){
  // Your existing code here

  // Write your code to handle employee id to print
  this.toPrint = this.project.employees.map(employee => employee.id)).join(", ")
}

And in your HTML:

{{toPrint}}
Sign up to request clarification or add additional context in comments.

Comments

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.