Tag: his int API ons SDI imp pre listen from
If you ' re coming from AngularJS (v1.x) probably remember the and ng-true-value
ng-false-value
directive which allowed to map custom Boo Lean values like "yes" or "no" or whatever other value of you had, onto your HTML form. In this lesson we ' re going to implement our own trueFalseValue
directive for Angular, by directly hooking into Angular ' s form API. A Nice occasion to learn about the ControlValueAccessor
interface.
Import {Directive, Input, Elementref, Renderer2, Hostlistener, forwardref} from ' @angular/core '; import {controlvalueaccessor, ng_value_accessor} from' @angular/forms '; @Directive ({selector:' Input[type=checkbox][truefalsevalue] ', providers: [{provide:ng_value_accessor, useexisting:forwardref ()=truefalsevaluedirective), Multi:true}]}) Export class Truefalsevaluedirective implements Controlvalueaccessor {@Input () TrueValue=true; @Input () Falsevalue=false; Private Propagatechange= (_: any) = = { }; Constructor (private elementref:elementref, Private Renderer:renderer2) {} @HostListener (' Change ', [' $event ']) onhostchange (EV) { This. Propagatechange (ev.target.checked? This. TrueValue: This. Falsevalue); } writevalue (Obj:any):void { //Model --View if(obj = = = This. TrueValue) { //this.elementRef.nativeElement.checked = true; This. Renderer.setproperty ( This. elementref.nativeelement, ' checked ',true); } Else { This. Renderer.setproperty ( This. elementref.nativeelement, ' checked ',false); }} registeronchange (Fn:any):void { This. Propagatechange =fn; } registerontouched (Fn:any):void{} setdisabledstate? (isdisabled:Boolean):void { }}
How to use:
<type= "checkbox" formcontrolname= "Lovingangular" Truefalsevalue truevalue= "Yes" falsevalue= "Nope" > Loving Angular?
[Angular] Create a ng-true-value and Ng-false-value in Angular by Controlvalueaccessor