Let's talk about how we can dynamically bind an input to an undefined property in an object. For example, we have an object named user
:
let user = {};
How can we bind an input to a property that doesn't exist yet? Like this:
<input [(ngModel)]="user.name" placeholder="Enter your name"></input>
What we want is for the ngModel
directive to create the undefined property as the user enters their name, resulting in:
user = {name: "John"};
But can we do this for nested properties as well? For instance:
<input [(ngModel)]="user.homeaddress.postcode" placeholder="Enter your post code"></input>
To end up with:
user = {name: "John", homeaddress: {postcode: "E20 1QS"}};