Search code examples
angularangular2-formsangular2-services

angular 2 form validation not working using hash form element


I have one form validation using angular 2.[Angular 2 Only] How to start validation part using below the way?

app.component.html:

<form   #registrationForm="ngForm"  (ngSubmit)="submitform()">
  <input type="text" class="form-control" name="name" formControlName="name" />
</form>

app.component.ts:

import { Component, Input, OnInit } from '@angular/core';
import { FormBuilder,FormGroup,Validators } from '@angular/forms';

export class AppComponent implements OnInit {
  ngForm: FormGroup;
  ngOnInit() {
    this.ngForm = this._fb.group({
      name: ['Select', Validators.required]
    });
  }
  submitform() {
    this.formSubmitted = true;
    if (!this.ngForm.valid) {
      alert("Form Not valid");
    } else {
      alert("Valid");
    }
  }
}

Above the script is not working..Where i did mistake?


Solution

  • There's an Issue with your Template. Instead of using #registrationForm="ngForm" use [formGroup]="ngForm"

    You're using a Reactive Form approach and in that, to map the form on the template, with the form on the Component, you use [formGroup] on the form tag in your template.

    #registrationForm="ngForm" is generally used in the Template Drive strategy of building forms. Then on (submit) you also pass the form to the method which isn't really required in this case.

    Also, you should be using (submit) instead of (ngSubmit)

    Try this:

    <form [formGroup]="ngForm" (submit)="submitform()">
      <input type="text" class="form-control" name="name" formControlName="name" />
      <button>Submit</button>
    </form>
    

    Here's a Sample StackBlitz for your ref.