[Angular] Create a ng-true-value and ng-false-value in Angular by controlValueAccessor
2024-08-31 13:19:10
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?
最新文章
- jQuery模拟打字逐字输出代码
- emacs 新手笔记(三) —— 为 emacs 做一点简单的定制
- DataTable添加行和列数据
- C#连接MySql数据库的方法
- BZOJ_1821_[JSOI2010]_部落划分_(贪心,并查集)
- Mvc学习笔记(4)
- Python安装及开发环境配置
- js 模拟QQ聊天窗口图片播放效果(带滚轮缩放)
- 使用Spring Cloud搭建服务注册中心
- Vue-admin工作整理(十五):Ajax-跨域问题
- hbase版本升级的api对比
- Https协议报错:com.sun.net.ssl.internal.www.protocol.https.HttpsURLConnectionOldImpl解决方法
- chrome 开发者工具,查看元素 hover 样式
- 点9图 Android设计中如何切图.9.png
- Python全栈学习_day004作业
- 自定义指令 格式化input数据为非负整数
- NOIP2018考前抱佛脚——搜索复习
- 转 Fiddler导出jmeter脚本
- fluentValidation集成到autofac
- Python面试题之Python反射详解
热门文章
- spring boot学习(转)
- 一个HTTP连接是包含两部分的,请求报文和响应报文这俩组合起来才是一次完整的HTTP请求,并不会单独显示请求报文或者响应报文
- Linux进程的内存布局
- the process android.process.acore has stopped或the process com.phone。。。。
- bzoj3262: 陌上花开(cdq分治+树状数组)
- Redis和Memcache和MongoDB简介及区别分析(整理)
- Linux下grub的配置文件
- http协议无状态中的 ";状态"; 到底指的是什么?!(转载)
- Creating a New Master Page in SharePoint 2013
- 【参考】JDBC执行存储过程的四种情况