Search code examples
angularformsngmodel

How is FormGroup directive used in template driven forms?


I understand that an instance of FormGroup in a component's class can be linked to the form in the template in Reactive Forms to validate its input fields. However I do not get how do we use FormGroup in Template-driven forms. What is the difference between ngModel and FormGroup?


Solution

  • Template-driven Forms: FormGroup

    In template driven forms, Angular binds to the FormGroup directive automatically when you use the <form> tag in your application.

    enter image description here

    As shown in the diagram, you can use a template reference variable (denoted with a #) to get the reference to the FormGroup. This then gives you access to the form state, such as the validity state so you can do things like disable a Save button until the values are valid.

     <button type="submit"
             [disabled]="!signupForm.valid">
       Save
      </button>
    

    You don't have to define a template reference variable for the form ... only if you need it as shown in the button example above.

    Template-driven Forms: ngModel

    You use ngModel to two-way bind an input element on the form with a property in the component. In the example below, we bind the input element to a customer.firstName property in the component.

    enter image description here

    By using ngModel and setting the name attribute, Angular will automatically define a FormControl for the control and add it to the FormGroup

    Here again we can use a template reference variable (denoted with a #) to reference the FormControl and access the control's state, such as touched or dirty or validation errors.

    This is often used to display validation error message like this:

    <span *ngIf="firstNameVar.errors">
      Please enter your first name.
    </span>