Reputation: 1
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!
Upvotes: 0
Views: 185
Reputation: 2742
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}}
Upvotes: 2