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

If you‘re coming from AngularJS (v1.x) you probably remember the ng-true-value and ng-false-value directive which allowed to map custom boolean values like "yes" or "no" or whatever other value 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:

      <input type="checkbox" formControlName="lovingAngular"
        trueFalseValue
        trueValue="yes" falseValue="nope"
        > loving Angular?

原文地址:https://www.cnblogs.com/Answer1215/p/8408499.html

时间: 2024-08-27 20:24:36

[Angular] Create a ng-true-value and ng-false-value in Angular by controlValueAccessor的相关文章

今天面试问了一道题。说一串字符串由这几个符号组成&quot;&lt;&gt;{}[]()”,写一个算法,例如如果组成方式为“&lt;&gt;{[]}{}()”这种,也就是XML格式那种则返回true。否则返回false;

原创 今天面试问了一道题.说一串字符串由这几个符号组成"<>{}[]()",写一个算法,例如如果组成方式为"<>{[]}{}()"这种,也就是XML格式那种则返回true.否则返回false: 当时没想出来, 只想到了回文数解决办法.回文数解决办法是颠倒比较,相等为true: 换xml格式当时真没想到啥好方法: 在回来的路上想到了.. .. 去重,吧临近的一组去掉,在递归调用比较去重直到最后,如果有剩下则不返回false:否则true: 代码

Python 字典(Dictionary) has_key()方法-判断键是否存在于字典中,如果键在字典dict里返回true,否则返回false

描述 Python 字典(Dictionary) has_key() 函数用于判断键是否存在于字典中,如果键在字典dict里返回true,否则返回false. 语法 has_key()方法语法: dict.has_key(key) 参数 key -- 要在字典中查找的键. 返回值 如果键在字典里返回true,否则返回false. 实例 以下实例展示了 has_key()函数的使用方法: #!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7} pri

python 中的True和1及False和0是可以等价比较

python 中的True和1及False和0是可以等价比较的测试如下: [[email protected] root]# cat test_true_false.py ok=0if ok:    print okok=1 if ok:    print okok=True if ok:    print okok=False if ok:    print ok print '*'*20 ok=0if ok == False:    print ok ok=1if ok == True:  

angular中出现错误的提示指令[ng:areq]的原因

angular.min.js:80 Error: [ng:areq] http://errors.angularjs.org/1.2.9/ng/areq?p0=sellerService&p1=not%20a%20function%2C%20got%20undefined at angular.min.js:2 at ub (angular.min.js:14) at Pa (angular.min.js:14) at angular.min.js:57 at angular.min.js:45

[Angular] Create custom validators for formControl and formGroup

Creating custom validators is easy, just create a class inject AbstractControl. Here is the form we want to validate it: form = this.fb.group({ store: this.fb.group({ branch: ['', [Validators.required, StockValidators.checkBranch]], code: ['', Valida

[Angular] Create a custom validator for reactive forms in Angular

Also check: directive for form validation User input validation is a core part of creating proper HTML forms. Form validators not only help you to get better quality data but they also guide the user through your form. Angular comes with a series of

[Angular] Remove divs to Preserve Style and Layout with ng-container in Angular

The Angular <ng-container> is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM. When we using Content Projection in a DUMP component: <div class="card" style="width: 18rem;&q

转:request.getSession(true)和request.getSession(false)的区别

转自:http://www.cnblogs.com/tv151579/p/3870905.html 1.转自:http://wenda.so.com/q/1366414933061950?src=150 概括: request.getSession(true):若存在会话则返回该会话,否则新建一个会话. request.getSession(false):若存在会话则返回该会话,否则返回NULL ==================================================

request.getSession(true)和request.getSession(false)的区别

request.getSession(true):若存在会话则返回该会话,否则新建一个会话. request.getSession(false):若存在会话则返回该会话,否则返回NULL. 三种重载方法 现实中我们经常会遇到以下3种用法: HttpSession session = request.getSession(); HttpSession session = request.getSession(true); HttpSession session = request.getSessi