Craft your own custom form control

Web application making

  • Library / Framework / Vanilla
  • If need statement management
  • CSS Framework
  • Various controls

@pankajparkar

Forms

  • Pristine
  • dirty
  • valid / invalid
  • touched / untouched

@pankajparkar

Pankaj P. Parkar

Technical Lead, Synerzip

  • 1x Engineer 😂

  • MS MVP

  • Angular GDE

  • Opensource Maintainer

  • Stackoverflow Topuser

About Me!

@pankajparkar

(@ngx-lib/multiselect)

Let's assume requirement

(too specific and simpler requirement)

@pankajparkar

Need of creating custom control

@pankajparkar

  • Can't use template driven form
  • Applying validation dynamically can be challenging
  • Could lead to unmaintainable code

ControlValueAccessor

Accesor Form Element
DefaultValueAccessor input, textarea
CheckboxControlValueAccessor input[type=checkbox]
NumberValueAccessor input[type=number]
RadioControlValueAccessor input[type=radio] 
RangeValueAccessor input[type=range]
SelectControlValueAccessor select
SelectMultipleControlValueAccessor select[multiple] 

Above all classes inherits from ControlValueAccessor

CVA API

  • writeValue
  • registerOnChange
  • registerOnTouched

  • setDisabled

@pankajparkar

Extend Provider

const DEFAUL_CONTROLVALUEACCESSOR: Provider = {
  provide: NG_VALUE_ACCESSOR,
  multi: true,
  useExisting: forwardRef(() => RadioGroupComponent)
}

Let's Code

@pankajparkar

Extract Code to Library

@pankajparkar

@ngx-lib/multiselect

@pankajparkar

Demo

Take Away

@pankajparkar

@pankajparkar

References

@pankajparkar

Create your own custom form control

By Pankaj Parkar

Create your own custom form control

  • 983