Angular 如何设置到有效引用但为空/新对象的双向绑定

Angular 如何设置到有效引用但为空/新对象的双向绑定,angular,typescript,angular5,Angular,Typescript,Angular5,在所有属性都有效但为空的情况下,如何正确设置与类对象的绑定 有效…如果组件声明为: export class BioComponent implements OnInit { bio : Bio = { id : 1, FirstName : "", LastName : ""}; constructor() { } ngOnInit() { } } 在用户编辑的视图中,以下绑定起作用,下面的第三行显示了用户键入的内容 <td><input [(ngM

在所有属性都有效但为空的情况下,如何正确设置与类对象的绑定


有效…如果组件声明为:

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.FirstName+''+bio.LastName}

失败

如果
bio:bio=new bio(),然后第三项显示
undefined undefined
,直到用户为每个输入输入输入内容



总而言之我不希望每个属性都有类似
FirstName:,
属性声明这样的东西。如何在Angular/TypeScript中创建新对象?

您可以在
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()将使用默认值初始化。

您可以使用默认值在构造函数中定义和初始化数据成员:

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');

您可以在中看到正在工作的代码。

您可以直接在构造函数中声明成员。但这不会默认值吗?不,您可以设置默认值。@ConnorsFan我很好奇,请告诉我:D