angular - 有人可以解释为什么打印显示“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 中获取所选对象。我怎样才能实现它?
非常感谢您的帮助
谢谢你
解决方案
因为您在 [ngValue]="contactList" 中绑定了contactList,所以在contactListChanged($event) 中选择的对象选择名称将contactList.name 绑定到ngValue,如下所示
<option *ngFor="let contactList of contactLists" [ngValue]="contactList.name">{{ contactList.name }}</option>
如果您只传递字符串,您也可以使用值。两者之间的唯一区别是值始终是字符串,在 ngValue 中您可以传递对象。
推荐阅读
- jquery - 为什么 Apache 不从 ajax POST 保存 XML 文件?
- python - 第一个搜索程序 - 用于机器人路径打印的人工智能
- spring-boot - 如何在不使用 npm 的情况下生成 material-components-web css 主题?
- c# - 如何将身份验证代码从 .Net Framework 中的 IdentityServer3 迁移到 .Net Core 2.2 中的 IdentityServer4?
- javascript - 我们如何正确使用 React Dnd 与可多次拖动的同一项目并附加到反应状态数组
- python - 使用 Flask 和 Flask-Admin 时如何修复“register_blueprint”错误?
- css - Instagram 如何拥有“干净”的字体?
- reactjs - 我的 Salesforce 组织中发生错误。渲染没有返回任何内容
- python - 如何打印正则表达式的一部分
- swift - 用于观察 Swift 5 变化的通用协议