Please find explanation of Angular 2 ngForm in below link:

http://www.catchexceptions.com/html/angular-2-ngform-with-ngmodel-directive/

This is the another way of implementing ngForm of Angular 2. Please find below the working code of how to use ngForm with all validations :

app.component.html

<div class="container">
<div>
<h1>Login Form</h1>
<form (ngSubmit)="onSubmit()" #loginForm="ngForm">
<div>
<label for="name">Name</label>
<input type="text" id="name" required [(ngModel)]="model.name" name="name" #name="ngModel">
<div [hidden]="name.valid || name.pristine" >
Name is required
</div>
</div>

<div>
<label for="password">Password</label>
<input type="password" id="password" [(ngModel)]="model.password" name="password" required #password="ngModel">
<div [hidden]="password.valid || password.pristine" >
Password is required
</div>
</div>

<button type="submit" [disabled]="!loginForm.form.valid">Submit</button>
<button type="button" (click)="loginForm.reset()">Reset</button>
</form>
</div>
</div>

app.component.css

.ng-valid[required], .ng-valid.required {
border-left: 5px solid #42A948; /* green */
}

.ng-invalid:not(form) {
border-left: 5px solid #a94442; /* red */
}

app.component.ts

import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { NgForm } from '@angular/forms';
import { User } from './user.to';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor() {

}

model = new User();

onSubmit() {
console.log(this.model.name);
console.log(this.model.password);
}
}

user.to.ts

export class User {
public name: string;
public password: string;
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms'
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule, FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Angular 2 NgForm with NgModel(two way data binding)
Tagged on:                 

Leave a Reply

Your email address will not be published. Required fields are marked *