最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Typescript - Bind ngModel to property of object - Stack Overflow

programmeradmin2浏览0评论

I have an object called user:

let user = {};

How can I bind an input to a undefined property? E.g.

<input [(ngModel)]="user.name" placeholder="Enter your name"></input>

And whenever the user enters his name, I want the ngModel to create the undefined property of that object and result in this:

user = {name: "John"};

Is this also possible to be done at deepter levels? E.g.

<input [(ngModel)]="user.homeaddress.postcode" placeholder="Enter your post code"></input>

to result in:

user = {name: "John", homeaddress: {postcode: "E20 1QS"}};

I have an object called user:

let user = {};

How can I bind an input to a undefined property? E.g.

<input [(ngModel)]="user.name" placeholder="Enter your name"></input>

And whenever the user enters his name, I want the ngModel to create the undefined property of that object and result in this:

user = {name: "John"};

Is this also possible to be done at deepter levels? E.g.

<input [(ngModel)]="user.homeaddress.postcode" placeholder="Enter your post code"></input>

to result in:

user = {name: "John", homeaddress: {postcode: "E20 1QS"}};
Share Improve this question edited Aug 28, 2018 at 23:52 EDJ asked Aug 28, 2018 at 23:46 EDJEDJ 1,0334 gold badges20 silver badges43 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

Two way data binding supports any nested objects, you just need to use it as,

<input [(ngModel)]="user.homeaddress.postcode" placeholder="Enter your post code"></input>

since you have initialized data it wont throw any error.

Is this also possible to be done at deepter levels?

Yes. "user.homeaddress.postcode" will work.

发布评论

评论列表(0)

  1. 暂无评论