【问题标题】:Complex two way data binding with ngModel使用 ngModel 进行复杂的双向数据绑定
【发布时间】:2017-09-10 20:37:05
【问题描述】:

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

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
}

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

谢谢

【问题讨论】:

    标签: angular angular-ngmodel


    【解决方案1】:

    将 [(ngModel)]="buyer" 更改为 [(ngModel)]="buyer.firstName" 或任何拥有买家的房产名称

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

    【讨论】:

    • 这是双向绑定的正常方式,显示一个字符串并将其绑定到另一个字符串,如buyer.firstName。我试图做一个更棘手的想法,在输入中显示一个字符串并将其绑定到从自动完成中选择它的对象。
    猜你喜欢
    • 1970-01-01
    • 2017-10-19
    • 1970-01-01
    • 2016-10-12
    • 2021-09-02
    • 2020-09-12
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    相关资源
    最近更新 更多