[Angular] Create a ng-true-value and Ng-false-value in Angular by Controlvalueaccessor

Source: Internet
Author: User
Tags export class html form

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.