Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - Bind ngModel to property of object

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"}};
like image 705
EDJ Avatar asked Nov 07 '22 02:11

EDJ


1 Answers

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.

like image 111
Sajeetharan Avatar answered Nov 14 '22 21:11

Sajeetharan