custom form control 之前就写过了,这里简单写一下.

创建一个组件实现 ControlValueAccessor 接口

@Component({
providers: [
{ provide: NG_VALUE_ACCESSOR, multi: true, useExisting: MyInputComponent },
],
})
export class MyInputComponent implements ControlValueAccessor {}

实现 writeValue, model -> view 的时候被调用的,这里实现如何更新 view. 如果时 OnPush 记得要 markForCheck

writeValue(value: any): void {
console.log('writeValue');
this.cdr.markForCheck();
this.value = value;
}

实现 registerOnChange 方法. view -> model 内部通过调用这个方法向外输出值

private onChangeFn: (value: any) => void;
registerOnChange(fn: MyInputComponent['onChangeFn']): void {
this.onChangeFn = fn;
}

实现 registerOnTouched 方法, view -> model, 当内部 touched 了通知外部

private onTouchedFn: () => void;
registerOnTouched(fn: MyInputComponent['onTouchedFn']): void {
console.log('registerOnTouched');
this.onTouchedFn = fn;
}

实现 setDisabledState 方法, model -> view, 当外部设定 disabled 后, 内部更新 view

setDisabledState(isDisabled: boolean): void {
console.log('setDisabledState');
this.cdr.markForCheck();
this.disabled = isDisabled;
}

执行的顺序是 ngOnInit-> DoCheck -> writeValue-> registerOnChange -> registerOnTouched -> setDisabledState -> ngAfterContentInit ...

实现好了 customer accessor 现在我们来把它放进 mat form filed 里

refer https://material.angular.io/guide/creating-a-custom-form-field-control

要做到这一点, 组件必须实现 MatFormFieldControl 里面有 14 个接口要实现的.

@Directive()
export abstract class MatFormFieldControl<T> {
value: T | null;
readonly stateChanges: Observable<void>;
readonly id: string;
readonly placeholder: string;
readonly ngControl: NgControl | null;
readonly focused: boolean;
readonly empty: boolean;
readonly shouldLabelFloat: boolean;
readonly required: boolean;
readonly disabled: boolean;
readonly errorState: boolean;
readonly controlType?: string;
readonly autofilled?: boolean;
abstract setDescribedByIds(ids: string[]): void;
abstract onContainerClick(event: MouseEvent): void;
}

还需要提供 provider, 这里要注意 : 由于我们的组件本身就是 value accessor 所以我们需要动一点手脚, 删除 provide NG_VALUE_ACCESSOR 改用 ngControl.valueAccessor = this 的方式去做.

@Component({
providers: [
{ provide: MatFormFieldControl, useExisting: MyInputComponent },
// { provide: NG_VALUE_ACCESSOR, multi: true, useExisting: MyInputComponent },
],
})
export class MyInputComponent implements MatFormFieldControl<Value> {
constructor(
@Optional() @Self() public ngControl: NgControl, ) {
if (ngControl != null) {
ngControl.valueAccessor = this;
}
}
}

其它部分都很好理解.

stateChanges 是用来通知 form field 要 mark for check 的, 当我们内部修改后,要通知它就用这个.

要记得释放

ngOnDestroy() {
this.stateChanges.complete();
this.focusMonitor.stopMonitoring(this.hostElement.nativeElement);
}

其它的都是一些属性. 一般上会使用 getter setter 去维护更新,比如

public get focused(): boolean {
return this._focused;
}
public set focused(v: boolean) {
this._focused = v;
this.stateChanges.next();
}
private _focused: boolean;

比如

get empty() {
return this.value === '';
} get shouldLabelFloat() {
return this.focused || !this.empty;
}

关于 focus 通常使用 monitor 来监听

focusMonitor.monitor(hostElement.nativeElement, true).subscribe(origin => {
this.focused = origin === null ? false : true;
});
onContainerClick
当用户点击内部组件时, 这个也会触发哦,可以通过 event.target 确认用户点击的是内部组件或者真的是外部的 container 做相应的处理
onContainerClick(event: MouseEvent) {
// if ((event.target as Element).tagName.toLowerCase() != 'input') {
// this.elRef.nativeElement.querySelector('input').focus();
// }
}
errorState 是一个比较烦人的东西
这个是用在做什么时候需要显示 error 的情况.form field 本身是不处理这个的,是交由 accessor 管理的. 
material 有一个叫 errorStateMatcher 的 class 我们的组件最好也可以支持这样的设定,这样就比较统一. 
下面是 input 的做法.
   <input matInput placeholder="Email" [formControl]="emailFormControl"
[errorStateMatcher]="matcher">
 
 

Angular 学习笔记 (Custom Accessor + Mat FormField + Custom select)的更多相关文章

  1. Angular 学习笔记 ( CDK - Accessibility )

    @angular/ckd 是 ng 对于 ui 组建的基础架构. 是由 material 团队开发与维护的, 之所以会有 cdk 看样子是因为在开发 material 的时候随便抽象一个层次出来给大家 ...

  2. angular学习笔记(三十一)-$location(2)

    之前已经介绍了$location服务的基本用法:angular学习笔记(三十一)-$location(1). 这篇是上一篇的进阶,介绍$location的配置,兼容各版本浏览器,等. *注意,这里介绍 ...

  3. angular学习笔记(三十一)-$location(1)

    本篇介绍angular中的$location服务的基本用法,下一篇介绍它的复杂的用法. $location服务的主要作用是用于获取当前url以及改变当前的url,并且存入历史记录. 一. 获取url的 ...

  4. angular学习笔记(三十)-指令(10)-require和controller

    本篇介绍指令的最后两个属性,require和controller 当一个指令需要和父元素指令进行通信的时候,它们就会用到这两个属性,什么意思还是要看栗子: html: <outer‐direct ...

  5. angular学习笔记(三十)-指令(7)-compile和link(2)

    继续上一篇:angular学习笔记(三十)-指令(7)-compile和link(1) 上一篇讲了compile函数的基本概念,接下来详细讲解compile和link的执行顺序. 看一段三个指令嵌套的 ...

  6. angular学习笔记(三十)-指令(7)-compile和link(1)

    这篇主要讲解指令中的compile,以及它和link的微妙的关系. link函数在之前已经讲过了,而compile函数,它和link函数是不能共存的,如果定义了compile属性又定义link属性,那 ...

  7. angular学习笔记(三十)-指令(6)-transclude()方法(又称linker()方法)-模拟ng-repeat指令

    在angular学习笔记(三十)-指令(4)-transclude文章的末尾提到了,如果在指令中需要反复使用被嵌套的那一坨,需要使用transclude()方法. 在angular学习笔记(三十)-指 ...

  8. angular学习笔记(三十)-指令(5)-link

    这篇主要介绍angular指令中的link属性: link:function(scope,iEle,iAttrs,ctrl,linker){ .... } link属性值为一个函数,这个函数有五个参数 ...

  9. angular学习笔记(三十)-指令(2)-restrice,replace,template

    本篇主要讲解指令中的 restrict属性, replace属性, template属性 这三个属性 一. restrict: 字符串.定义指令在视图中的使用方式,一共有四种使用方式: 1. 元素: ...

随机推荐

  1. PPR管各种接头产品名称

    PPR管各种接头产品名称 http://ishare.iask.sina.com.cn/f/19n7gOsntbX.html

  2. GIS地理工具案例教程——合并选中图层

    GIS地理工具案例教程--合并选中图层 商务合作,科技咨询,版权转让:向日葵,135-4855__4328,xiexiaokui#qq.com 功能:并图层列表中 描述:对图层列表中选中图层进行合并. ...

  3. Hive小文件处理

    小文件是如何产生的: 动态分区插入数据的时候,会产生大量的小文件,从而导致map数量的暴增 数据源本身就包含有大量的小文件 reduce个数越多,生成的小文件也越多 小文件的危害: 从HIVE角度来看 ...

  4. Python3基础 输出逐行递增的小星星

             Python : 3.7.3          OS : Ubuntu 18.04.2 LTS         IDE : pycharm-community-2019.1.3    ...

  5. Dart中的数据类型转换:

    int -> string age.toString() string -> int int.parse('100'); String -> double 1 var onePoin ...

  6. *438. Find All Anagrams in a String 找到字符串中所有字母异位词

    1. 原始题目 给定一个字符串 s 和一个非空字符串 p,找到 s 中所有是 p 的字母异位词的子串,返回这些子串的起始索引. 字符串只包含小写英文字母,并且字符串 s 和 p 的长度都不超过 201 ...

  7. build doris 0.11.5 on centos 7/ubuntu

    doris has envolved many thirdparty components since v0.9. so the build progress has changed a lot si ...

  8. django项目mysite

    项目建立 建立项目mysite 各文件和目录解释: 外层的mysite/目录与Django无关,只是你项目的容器,可以任意重命名. manage.py:一个命令行工具,用于与Django进行不同方式的 ...

  9. Eureka 与 zookeeper 的区别、

    前言在微服务的开发过程中,如果使用的是 Dubbo 那就必须使用到 Zookeeper ,在使用 Spring Cloud Eureka 时,自然其功能更强大得多.博主也不得不感叹,Spring Cl ...

  10. TroubleShooting经验总结

    1.WinDbg是微软开发的免费源代码级的调试工具.WinDbg可以用于Kernel模式调试和用户模式调试,还可以调试Dump文件.WinDbg对于dump文件的调试可以通过菜单设置Symbol Fi ...