首页 > 解决方案 > 有人可以解释为什么打印显示“2:对象”的选项值吗?

问题描述

您好目前我使用 angular 5 和 typescript 开发了 UI。在我的一个组件中,我有一个反应式表单,在组件视图中,我有选择框表单控件。所以我想要的是每当我从选择框中选择不同的选项时,它应该打印选择的值。所以我在我的组件类中注册了一个函数contactListChanged。

<select formControlName="contactList" [compareWith]="compareResource" (change)="contactListChanged($event)">
<option value="" disabled>{{ 'PLACEHOLDERS.CONTACT_LIST' | translate }}</option>
<option *ngFor="let contactList of contactLists" [ngValue]="contactList">{{ contactList.name }}</option>
</select>

在组件 ts 文件中

  contactListChanged($event){
    let a  = $event.target.value ;
    console.log(a);// prints 1: Object

    console.log(this.contactListControl.value); // prints Object {id: "1", name: "irish msisdn 1", total: 1000, displayName: "irish msisdn 2(1000)"}
  }

console.log(a) 打印值“2:对象”。但是 console.log(this.contactListControl.value); 正确打印值。对象{id:“2”,名称:“irish msisdn 2”,总数:1200,displayName:“irish msisdn 2(1200)”}

为什么是这种行为?我希望 console.log(a) 打印值 Object {id: "2", name: "irish msisdn 2", total: 1200, displayName: "irish msisdn 2(1200)"}

所以我想要的是使用 [ngValue] 并在方法 contactListChanged 中获取所选对象。我怎样才能实现它?

非常感谢您的帮助

谢谢你

标签: angulartypescript

解决方案


因为您在 [ngValue]="contactList" 中绑定了contactList,所以在contactListChanged($event) 中选择的对象选择名称将contactList.name 绑定到ngValue,如下所示

<option *ngFor="let contactList of contactLists" [ngValue]="contactList.name">{{ contactList.name }}</option>

如果您只传递字符串,您也可以使用值。两者之间的唯一区别是值始终是字符串,在 ngValue 中您可以传递对象。


推荐阅读