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: '[email protected]' },
    { name: 'abc', email: '[email protected]' },
  ];

    ngOnInit() {
        this.UserDataNames.forEach((c, i) => {
            this.UserData.push({ id: i, name: c });
        });
    }

    addTagFn(name) {
        return { name: name, tag: true };
    }

enter image description here

For eg. :- UserData = [{name:'xyz',email:'[email protected]'},{name:'abc',email:'[email protected]'}]. When I am select [email protected] 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

1

There are 1 best solutions below

0
Yong Shun On BEST ANSWER

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,
}));

Demo @ StackBlitz