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

How To Setup a Two Way Binding To a Valid Reference but Empty/ New Object

如何正确设置绑定到所有属性都有效但为空的 class 对象?


有效...如果组件是这样声明的:

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 中新建一个新对象?

您可以在 Bio class 中设置默认值。

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

您可以在 this stackblitz.

中查看工作中的代码