typescript 我想在列表中显示电子邮件ID,我希望在选择电子邮件后,显示与该电子邮件相关的选定值

ni65a41a  于 12个月前  发布在  TypeScript
关注(0)|答案(1)|浏览(147)

我想在我的电子邮件列表中的电子邮件ID。每当我选择一个电子邮件,它会显示在输入字段的用户名.

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

例如:- UserData = [{name:'xyz ',email:' email protected(https://stackoverflow.com/cdn-cgi/l/email-protection) '},{name:'abc',email:' email protected(https://stackoverflow.com/cdn-cgi/l/email-protection) '}]。当我从列表中选择email protected(https://stackoverflow.com/cdn-cgi/l/email-protection)时,它将显示xyz作为选定值。我也发现了一些自定义templete解决方案,但它也不工作。它是这样显示的

toiithl6

toiithl61#

问题在于迭代UserDataNames数组并将元素添加到UserData数组中。

this.UserData.push({ id: i, name: c });

您正在将对象分配给name字段。没有email字段。
相反,您应该将元素添加到UserName数组中,如下所示:

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

或者你可以使用map函数:

this.UserData = this.UserDataNames.map((c, i) => ({
  id: i,
  name: c.name,
  email: c.email,
}));

Demo @ StackBlitz

相关问题