Showing posts with label Angular 4. Show all posts
Showing posts with label Angular 4. Show all posts

Friday, April 24, 2020

Angular CLI - Custom Date validator

Angular supports of custom validators. Here i have created custom validator to validate date for template drive forms.

Directive: date-validator.directive.ts


import { AbstractControl, ValidatorFn, FormControl } from '@angular/forms';
import * as moment from 'moment';
import { NG_VALIDATORS, Validator } from '@angular/forms';
import { Directive } from '@angular/core';

// validation function
function validateDateFactory(): ValidatorFn {
  return (c: AbstractControl) => {

    let isValid = moment(c.value, 'M/D/YYYY', true).isValid();

    if (isValid) {
      return null;
    } else {
      return {
        validDate: {
          valid: false
        }
      };
    }
  }
}

@Directive({
  selector: '[validDate][ngModel]',
  providers: [
    { provide: NG_VALIDATORS, useExisting: ValidDateValidator, multi: true }
  ]
})
export class ValidDateValidator implements Validator {
  validator: ValidatorFn;

  constructor() {
    this.validator = validateDateFactory();
  }

  validate(c: FormControl) {
    return this.validator(c);
  }

}


Html:
<input type="text" [(ngModel)]="someDateModal" validDate />

Monday, May 21, 2018

Angular 4 - How to detect device in browser

Its very simple and straight forward to use plugin for Angular 4 typescript as below

Use plugin https://www.npmjs.com/package/ngx-device-detector which can be added to package.json to install as reference

Include in your app.module as below

import { DeviceDetectorModule } from 'ngx-device-detector';


imports: [
      DeviceDetectorModule.forRoot()
    ],

Include in your component or service as below


import { DeviceDetectorService } from 'ngx-device-detector';

constructor(private deviceService: DeviceDetectorService) {   }

To get device info use as below in component

this.deviceService.getDeviceInfo();  //This will get all device useragent info 
this.deviceService.isTablet(); //This will get device is tablet or not
this.deviceService.isDesktop(); //This will get device is desktop or not
this.deviceService.isMobile(); //This will get device is mobile or not