⚠️ This lesson is retired and might contain outdated information.

Create a Basic Angular 2 ngModel Input

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet

ngModel is a very powerful feature of Angular 2, but it isn’t enabled by default. You need to import the Angular 2 FormsModule and use the proper syntax around the ngModel directive to enable the features (such as automatically updating from an ngModel) that you would expect.

This lesson starts with a Angular 2 hello world app. To quickly set that up use the angular cli which will set up the boilerplate needed to get started.

[00:00] Starting from an Angular 2 "Hello, World," if I create an input and then add an ngModel attribute to it and assign that to username, you'll see that nothing happens other than just an input being set up. That's because in your modules, where you define your module setup, you need more than just a browser setup, you also need the forms module.

[00:20] I'll go ahead and import that, and include it, and you'll see that username is now set to the ngModel or the value of the input, but I don't want the string of username, I actually want the value of username. Go ahead and create a username. We'll give this a value of John, and we'll see if that changes anything, but unfortunately not, because what it's doing is evaluating this as a string because we told it not to evaluate it.

[00:50] To evaluate this as a property or a field on this class, you have to put a square brackets around it. That way, when you save, it's going to go ahead and look up this username and assign it to ngModel. Now, you might think you could take that username and place it in some curly braces and that when you start typing -- you see it's John already -- but when I start typing, it doesn't add anything.

[01:13] That's because in my ngModel, if I want this two-way binding, where right now, it's inputting this and setting this. If I want to get that value out as an event, you also have to add the parens around it, so that every time the ngModel or the value of the input changes, it also sends out an event to update this. Now, if I delete and type something, you'll see this updating as well.