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

How does one properly setup the binding to a class object where all properties are valid but empty?


Works ...If the component is declared as such:

export class BioComponent implements OnInit {

 bio : Bio  = { id : 1, FirstName : "", LastName : ""};

  constructor() { }

  ngOnInit() {
  }
}

In the view as the user edits, the following bindings work and the third line below shows what the user has typed in.

<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>

Fails

If bio : Bio = new Bio(); is set, then the third item shows undefined undefined until the user types in something to each of the inputs.


To Sum Up I don't want to have to have things like FirstName : "", property declarations for each property. How does one new up a new object in Angular/TypeScript?


You can define and initialize the data members in the constructor, with default values:

export class Bio {

  constructor(
    public id: number = 0, 
    public firstName: string = '', 
    public lastName: string = '') {
  }
}

You can create Bio objects as follows:

bio1 = new Bio();
bio2 = new Bio(1);
bio3 = new Bio(2, 'Robert');
bio4 = new Bio(3, 'Jane', 'Smith');

You can see the code at work in this stackblitz.


You can in your Bio class setup a default value.

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;
  }
}

then in your component

bio: Bio = new Bio(); will be initialized with defaults.

链接地址: http://www.djcxy.com/p/40700.html

上一篇: 深拷贝和浅拷贝之间有什么区别?

下一篇: 如何设置一个双向绑定到一个有效的引用,但空/新对象