使用ngModel进行复杂的双向数据绑定

时间:2017-09-10 20:37:06

标签: angular angular-ngmodel

我首先在解释问题之前向您展示代码:



export class Person {
  firstName: string;
  lastName: string;
}

@Component({
  selector: 'app-person',
  template: `
    <input type="text" name="firstName" [(ngModel)]="buyer">
    <!-- Code for autocomplete, when selecting a person from the autocomplete, an object person is binded to buyer -->
  `
})
export class PersonComponent {
  buyer: Person;
  
  // Code for autocomplete
}
&#13;
&#13;
&#13;

我的问题是当用户从自动完成中选择一个人时,输入显示[object Object]这是正常的。如何使它显示firstName但将输入绑定到对象买方?

谢谢

1 个答案:

答案 0 :(得分:1)

将[(ngModel)] =“买方”更改为[(ngModel)] =“buyer.firstName”或任何拥有买方的属性名称

   <input type="text" name="firstName" [(ngModel)]="buyer.firstName">