angular-ts-basic-training


Project maintained by simon-an Hosted on GitHub Pages — Theme by mattgraham

Chapter 10 Pipes and Validators

Preparation: Ceate a simple register form with one input for email address

ng g component views/home/components/registerForm --changeDetection OnPush
Code
  • register-form.component.html
<form (ngSubmit)="onSubmit()" #registerForm="ngForm">
  <mat-form-field>
    <mat-select placeholder="Role" #roleInput [(value)]="state.role" matInput name="role" [(ngModel)]="state.role">
      <mat-option *ngFor="let role of roles" [value]="role">
        
      </mat-option>
    </mat-select>
  </mat-form-field>

  <mat-form-field>
    <input
      email
      required
      name="email"
      [(ngModel)]="state.email"
      matInput
      placeholder="Email"
      #email="ngModel"
      autocomplete="section-register email"
      [ngModelOptions]="{ updateOn: 'blur' }"
    />
    <mat-error *ngIf="email?.errors?.userExists">
      user does not exists
    </mat-error>
    <mat-error *ngIf="email?.errors?.email">
      Please enter a valid email address
    </mat-error>
    <mat-error *ngIf="email?.errors?.required"> Email is <strong>required</strong> </mat-error>
  </mat-form-field>

  <button [disabled]="!registerForm.valid" mat-button color="primary">
    Register
  </button>
  <mat-error *ngIf="!!registerForm.errors?.specialAdmin && (email.touched || email.dirty)">
    Email address domain for admins are restricted.
  </mat-error>
</form>
  • register-form.component.ts
import { Component, OnInit, ChangeDetectionStrategy } from "@angular/core";

@Component({
  selector: "cool-register-form",
  templateUrl: "./register-form.component.html",
  styleUrls: ["./register-form.component.scss"],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class RegisterFormComponent implements OnInit {
  roles = ["Customer", "Administrator"];
  state = { email: "", role: "Customer" };

  constructor() {}

  ngOnInit() {}

  onSubmit() {
    console.log("Register user with email: ", this.state.email);
  }
}
  • home-module.ts
import { NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";

import { HomeRoutingModule } from "./home-routing.module";
import { LayoutModule } from "~layout/layout.module";
import { SafeModule } from "~safe/safe.module";
import { HomeLandingPageComponent } from "./home-landing-page/home-landing-page.component";
import {
  MatListModule,
  MatFormFieldModule,
  MatInputModule,
  MatSelectModule
} from "@angular/material";
import { RegisterFormComponent } from "./components/register-form/register-form.component";
import { FormsModule } from "@angular/forms";

@NgModule({
  declarations: [HomeLandingPageComponent, RegisterFormComponent],
  imports: [
    CommonModule,
    HomeRoutingModule,
    LayoutModule,
    MatListModule,
    FormsModule,
    MatFormFieldModule,
    MatInputModule,
    MatSelectModule
  ]
})
export class HomeModule {}
  <div body><cool-register-form></cool-register-form></div>
emailExists
  emailExists(email: string): Promise<boolean> {
    return timer(300)
      .pipe(
        map(time => {
          if (
            Math.random()*100 < 20
          ) {
            return true;
          } else {
            return false;
          }
        })
      )
      .toPromise();
  }

Exercise 10.1 Create admin and email domain validator

ng generate directive views/home/directives/admin-email-validator SpecialAdminValidatorDirective --module home
import { Directive } from "@angular/core";
import {
  AbstractControl,
  ValidationErrors,
  ValidatorFn,import { Directive } from '@angular/core';
import { AbstractControl, ValidationErrors, ValidatorFn, FormGroup, Validator, NG_VALIDATORS } from '@angular/forms';

export const adminDomainValidator: ValidatorFn = (control: FormGroup): ValidationErrors | null => {
  const role = control.get('role');
  const email = control.get('email');

  console.log(role, email);

  return role && email && role.value === 'Administrator' && !email.value.includes('@metafinanz.de')
    ? { specialAdmin: true }
    : null;
};

@Directive({
  selector: '[coolAdminEmailValidator]',
  providers: [
    {
      provide: NG_VALIDATORS,
      useExisting: AdminEmailValidatorDirective,
      multi: true,
    },
  ],
})
export class AdminEmailValidatorDirective implements Validator {
  constructor() {}
  validate(control: AbstractControl): ValidationErrors | null {
    return adminDomainValidator(control);
  }
}

Exercise 10.2 Create user exists async validator

Solution

Create user-exists-validator.directive.ts

ng generate directive views/home/directives/user-exists-validator UserExistsValidatorDirective --module home
import { Directive } from "@angular/core";
import {
  AsyncValidator,
  ValidationErrors,
  AbstractControl,
  NG_ASYNC_VALIDATORS
} from "@angular/forms";
import { Observable, from } from "rxjs";
import { map, catchError, take } from "rxjs/operators";
import { AuthService } from "~core/services/auth.service";

@Directive({
  selector: "[coolUserExistsValidator]",
  providers: [
    {
      provide: NG_ASYNC_VALIDATORS,
      useExisting: UserExistsValidatorDirective,
      multi: true
    }
  ]
})
export class UserExistsValidatorDirective implements AsyncValidator {
  constructor(private service: AuthService) {}

  validate(
    ctrl: AbstractControl
  ): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> {
    console.log("UserExistsDirective", ctrl);
    return from(this.service.emailExists(ctrl.value)).pipe(
      map(isTaken => (isTaken ? { userExists: "user already exists" } : null)),
      catchError(() => null)
    );
  }
}

Exercise 10.3 Material Elevation: Docs

  <div body class="body">
    <h2>Welcome to the Cool Safe App.</h2>
    <p>Please login or register as a new user.</p>
    <cool-register-form></cool-register-form>
  </div>
home-landing-page.component.scss
@import "~@angular/material/theming";
.body {
  // Adds a shadow for elevation level 2 with default color and full opacity:
  @include mat-elevation(2);
  padding: 20px;
  margin: 10px;
}

Next