Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Group Inputs in Angular 2 Forms with ngModelGroup

    John LindquistJohn Lindquist
    2 - 6

    The ngModelGroup directive allows you to group together related inputs so that you structure the object represented by the form in a useful and predictable way. ngModelGroup is often used in combination with fieldset as they mostly represent the same idea of “grouping together inputs.”



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    To add a password to our form, we must add another input. We'll say the type is password and then the minimal required is saying this is an ngModel, you don't even have to assign it to anything. You do have to give it a name, though. We'll say the name is password.

    With that information in there, now you'll see when I update the password, it's updating it in the form object, because this form is finding this input with a name of password and saying that password is the value of this here, which is just characters I typed in.

    If I type in password, you'll see that password shows up here. When I submit as well, you'll see that the object is John, with a password of password. We can group inputs together inside the form. We'll use a field set and wrap out inputs inside of the field set.

    Tab these in a bit and if we save this as an ngModel group of login, and hit save, we'll now see our object is the root object with a property of login, which has an object of username and password. If I type password again and hit submit, you'll see that submit object has an object for login and that login is an object with a username and password.

    As you structure out your data and structure out your form, you can use ngModel groups with a property name to help structure out login and password. Then the names of the inputs are going to be the names of the properties inside of that model group.

    To contrast an input, this is the bare minimum you need, where you need ngModel, the directive on there with a name or pretty much the maximum is an input with a ref to the ngModel, it's own validation, validation rules as well as some default settings for assigning properties into that ngModel.

    As you build out your forms, you start with the absolute simplest, and then slowly start adding rules, and validators and other visuals to help guide the user.