如何设置一个双向绑定到一个有效的引用,但空/新对象
如何正确设置绑定到所有属性均为有效但空的类对象?
Works ...如果组件是这样声明的:
export class BioComponent implements OnInit {
 bio : Bio  = { id : 1, FirstName : "", LastName : ""};
  constructor() { }
  ngOnInit() {
  }
}
在用户编辑的视图中,下列绑定工作,下面的第三行显示用户输入的内容。
<td><input [(ngModel)]="bio.FirstName" placeholder="Your first name"></td>
<td><input [(ngModel)]="bio.LastName" placeholder="Your last name"></td>
<td>{{bio.FirstName + ' ' + bio.LastName}}</td>
失败
  如果bio : Bio = new Bio();  被设置,那么第三个项目显示undefined undefined直到用户输入一些东西到每个输入。 
  总结我不希望有像FirstName : "",这样的东西FirstName : "",每个属性的属性声明。  如何在Angular / TypeScript中新增一个新对象? 
您可以使用默认值在构造函数中定义和初始化数据成员:
export class Bio {
  constructor(
    public id: number = 0, 
    public firstName: string = '', 
    public lastName: string = '') {
  }
}
  您可以按如下方式创建Bio对象: 
bio1 = new Bio();
bio2 = new Bio(1);
bio3 = new Bio(2, 'Robert');
bio4 = new Bio(3, 'Jane', 'Smith');
你可以在这个stackblitz中看到工作中的代码。
  你可以在你的Bio课程中设置一个默认值。 
export class Bio {
  id: number;
  firstName: string;
  lastName: string;
  constructor(id: number = 0, first: string = '', last: string = '') {
      this.id = id;
      this.firstName = first;
      this.lastName = last;
  }
}
然后在你的组件中
 bio: Bio = new Bio();  将用默认值进行初始化。 
上一篇: How To Setup a Two Way Binding To a Valid Reference but Empty/ New Object
下一篇: Angular2/TypeScript component for objects of certain type
