angular4 – form

Just another way to create form in angular4.

  1. Create Factory for your form
  2. Use it in different components, for example: you have one module for mobile driven by ionic and another module for desktop. In these two modules you have the same forms, like login/register/user data.
  3. In this example used material design, in forms its necessary to show only one error line.

Factory class

import {FormBuilder, FormGroup, Validators} from '@angular/forms';
export class UserLoginFormFactory {

    static get(): FormGroup {
        return (new FormBuilder()).group({
            email: ['', [
                <any>Validators.required,
                <any>Validators.minLength(5),
                <any>Validators.pattern(/^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i)
            ]],
            password: ['', [
                <any>Validators.required,
                <any>Validators.minLength(5)
            ]],
        });
    }
}

Component

    ngOnInit() {
        this.loginForm = UserLoginFormFactory.get();
    }

Template


<form [formGroup]="loginForm" novalidate (ngSubmit)="save(loginForm.value, loginForm.valid)">

<div class="form-group text-center">
        <md-input-container>
            <input mdInput type="text" class="form-control" formControlName="email" name="email" placeholder="Email">
            <md-hint *ngIf="submitted && loginForm.hasError('required', ['email'])" class="text-danger">
                Email is required
            </md-hint>
            <md-hint *ngIf="submitted && loginForm.hasError('pattern', ['email'])" class="text-danger">
                Invalid email
            </md-hint>
            <md-hint *ngIf="submitted && loginForm.hasError('minlength', ['email'])" class="text-danger">
                Invalid length
            </md-hint>
        </md-input-container>
    </div>


<div class="form-group text-center">
        <md-input-container>
            <input mdInput type="password" class="form-control" formControlName="password" name="password" placeholder="password">
            <md-hint *ngIf="submitted && loginForm.hasError('required', ['password'])" class="text-danger">
                Password is required
            </md-hint>
            <md-hint *ngIf="submitted && loginForm.hasError('minlength', ['password'])" class="text-danger">
                Minimum length is 5
            </md-hint>
        </md-input-container>
    </div>


<div class="text-center">
        <button type="submit" class="btn btn-default" md-raised-button>Submit</button>
    </div>

</form>