Validation

HTML

<form [formGroup]="form">
    <div class="form-group">
        <label for="username">Username</label>
        <input 
        formControlName="username"
            id="username" 
            type="text" 
            class="form-control form-control-lg">
            <div *ngIf="username.touched && username.invalid" 
                 class="alert alert-danger">
                    <div *ngIf="username.errors.required">Username is required</div>
                    <div *ngIf="username.errors.minlength">
                        Username should be minimum  
                            {{ username.errors.minlength.requiredLength }}     
                        charatcers
                    </div>
                    <div *ngIf="username.errors.maxlength">
                        Username should be maximum  
                            {{ username.errors.maxlength.requiredLength }}     
                        charatcers
                    </div>
            </div>
    </div>
    <div class="form-group">
        <label for="password">Password</label>
        <input 
        formControlName="password"
            id="password" 
            type="text" 
            class="form-control form-control-lg">
    </div>
    <button class="btn btn-dark btn-lg" type="submit">
        Sign Up
    </button>
</form>

TS

import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'signup-form',
  templateUrl: './signup-form.component.html',
  styleUrls: ['./signup-form.component.scss']
})
export class SignupFormComponent {
  form = new FormGroup({
    username: new FormControl('', [
      Validators.required,
      Validators.minLength(3),
      Validators.maxLength(10),
    ]),
    password: new FormControl('', Validators.required)
  });

  get username() {
    return this.form.get('username');
  }
}
Was this page helpful?