I want email id's in my dropdown list. Whenever I select a email it will show the user name in input field.
<ng-select [items]="UserData" [addTag]="addTagFn" [hideSelected]="true" multiple="true"
bindLabel="name" class="ng-custom" appendTo="body" placeholder="User name [(ngModel)]="selectedValues">
<ng-template ng-option-tmp let-item="item" let-item$="item$" let-index="index">
{{item.email}}
</ng-template>
</ng-select>
.ts File
selectedValues;
UserData: any[] = [];
UserDataNames = [
{ name: 'xyz', email: 'xyz@email.com' },
{ name: 'abc', email: 'abc@email.com' },
];
ngOnInit() {
this.UserDataNames.forEach((c, i) => {
this.UserData.push({ id: i, name: c });
});
}
addTagFn(name) {
return { name: name, tag: true };
}
For eg. :- UserData = [{name:'xyz',email:'xyz@email.com'},{name:'abc',email:'abc@email.com'}]. When I am select xyz@email.com from the list It will show xyz as selected value. Also I found some custom templete solution but it is also not working.It is showing like this
The problem was when you were iterating the UserDataNames
array and adding the element in the UserData
array.
this.UserData.push({ id: i, name: c });
You are assigning the object to the name
field. And there is no email
field.
Instead, you should add the element to the UserName
array as:
this.UserDataNames.forEach((c, i) => {
this.UserData.push({ id: i, name: c.name, email: c.email });
});
Or you can work with the map
function:
this.UserData = this.UserDataNames.map((c, i) => ({
id: i,
name: c.name,
email: c.email,
}));