ng-true-value ng-false-value alternative in Angular

In AngularJs (1.x) there is facility to set true value and false value for input type checkbox using ngTrueValue ngFalseValue directives. But its been removed in Angular 2 +. Below is directive which will serve the same purpose as it was in AngularJs (1.x). Here it simply listens to the change event of input element using HostListener and value of input element is manipulated based on whether its checked or unchecked.

import {    Directive,    Input,    forwardRef,    HostListener,    ElementRef,    Renderer2} from '@angular/core';import {    ControlValueAccessor,    NG_VALUE_ACCESSOR,    NgControl} from '@angular/forms';@Directive({    selector: 'input[type=radio][trueFalseValue]',    providers: [        {            provide: NG_VALUE_ACCESSOR,            useExisting: forwardRef(() => TrueFalseValueDirective),            multi: true        }    ]})export class TrueFalseValueDirective implements ControlValueAccessor {    private propagateChange = (_: any) => {};    @Input() trueValue = true;    @Input() falseValue = false;    constructor(private elementRef: ElementRef, private renderer: Renderer2) {}    @HostListener('change', ['$event'])    onHostChange(ev) {        this.propagateChange( ? this.trueValue : this.falseValue);    }    writeValue(obj: any): void {        if (obj == null) {            this.propagateChange(this.falseValue);        }        if (obj === this.trueValue) {            this.renderer.setProperty(this.elementRef.nativeElement, 'checked', true);        } else {            this.renderer.setProperty(this.elementRef.nativeElement, 'checked', false);        }    }    registerOnChange(fn: any): void {        this.propagateChange = fn;        if (this.elementRef.nativeElement.value == null) {            this.propagateChange(this.falseValue);        }    }    registerOnTouched(fn: any): void {}    setDisabledState?(isDisabled: boolean): void {}}

How to use:

<input type="radio" trueFalseValue [trueValue]="someTrueValue" [falseValue]="someFalseValue"/>



Popular posts from this blog

MATLAB code for Circular Convolution using Matrix method

Positive number pipe in angular 2+