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?

最新文章

  1. jQuery模拟打字逐字输出代码
  2. emacs 新手笔记(三) —— 为 emacs 做一点简单的定制
  3. DataTable添加行和列数据
  4. C#连接MySql数据库的方法
  5. BZOJ_1821_[JSOI2010]_部落划分_(贪心,并查集)
  6. Mvc学习笔记(4)
  7. Python安装及开发环境配置
  8. js 模拟QQ聊天窗口图片播放效果(带滚轮缩放)
  9. 使用Spring Cloud搭建服务注册中心
  10. Vue-admin工作整理(十五):Ajax-跨域问题
  11. hbase版本升级的api对比
  12. Https协议报错:com.sun.net.ssl.internal.www.protocol.https.HttpsURLConnectionOldImpl解决方法
  13. chrome 开发者工具,查看元素 hover 样式
  14. 点9图 Android设计中如何切图.9.png
  15. Python全栈学习_day004作业
  16. 自定义指令 格式化input数据为非负整数
  17. NOIP2018考前抱佛脚——搜索复习
  18. 转 Fiddler导出jmeter脚本
  19. fluentValidation集成到autofac
  20. Python面试题之Python反射详解

热门文章

  1. spring boot学习(转)
  2. 一个HTTP连接是包含两部分的,请求报文和响应报文这俩组合起来才是一次完整的HTTP请求,并不会单独显示请求报文或者响应报文
  3. Linux进程的内存布局
  4. the process android.process.acore has stopped或the process com.phone。。。。
  5. bzoj3262: 陌上花开(cdq分治+树状数组)
  6. Redis和Memcache和MongoDB简介及区别分析(整理)
  7. Linux下grub的配置文件
  8. http协议无状态中的 &quot;状态&quot; 到底指的是什么?!(转载)
  9. Creating a New Master Page in SharePoint 2013
  10. 【参考】JDBC执行存储过程的四种情况