如何设置双向绑定到有效参考但空/新对象

时间:2018-01-14 22:02:17

标签: angular typescript angular5

如何正确设置绑定到类对象,其中所有属性都有效但是空?

工作 ...如果组件声明如此:

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 : "",属性声明等内容。如何在Angular / TypeScript中新建一个新对象?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

您可以使用默认值:

在构造函数中定义和初始化数据成员
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');

您可以在this stackblitz中看到代码正常工作。