Angular中如何通过指令前置textMask属性并使其被掩码模块识别?
解决Angular中自动为matDatepicker输入框添加text-mask的问题
首先来说你第一个方案的问题:你用Renderer动态添加[textMask]属性是行不通的。Angular的属性绑定(带方括号的那种)是在编译阶段解析的,运行时通过Renderer添加这种属性字符串,Angular不会把它当成真正的指令绑定来处理,所以text-mask模块根本识别不了这个配置。
然后看你第二个继承MaskedInputDirective的方案,出现的NullInjectorError: No provider for Boolean!是因为_compositionMode这个参数不能直接这么注入。它是Angular内部的一个依赖,需要用特定的令牌COMPOSITION_MODE来注入,而且这个依赖是可选的,得加上@Optional()装饰器。
下面是修正后的完整代码:
import { Directive, ElementRef, Renderer2, Optional, Inject } from '@angular/core'; import { MaskedInputDirective, TextMaskConfig } from 'angular2-text-mask'; import { COMPOSITION_MODE } from '@angular/core'; @Directive({ selector: 'input[matDatepicker]' }) export class DateMaskDirective extends MaskedInputDirective { public textMaskConfig: TextMaskConfig = { mask: [/[0-3]/, /\d/, "/", /[0-1]/, /\d/, "/", /[12]/, /[09]/, /\d/, /\d/], guide: true, placeholderChar: '\u2000', keepCharPositions: true, showMask: true }; constructor( el: ElementRef<any>, renderer: Renderer2, @Optional() @Inject(COMPOSITION_MODE) _compositionMode: boolean | null ) { super(renderer, el, _compositionMode ?? false); // 处理null的情况,默认传false } }
关键说明:
- 导入
COMPOSITION_MODE令牌,并用@Optional()和@Inject()来注入_compositionMode,这样就不会因为找不到提供者而报错了。 - 构造函数里用
_compositionMode ?? false处理可能的null值,确保传给父类的是布尔值。 - 这个指令会自动匹配所有带
matDatepicker属性的input元素,继承自MaskedInputDirective后,会自动应用你配置的textMaskConfig,不需要手动加textMask属性了。
最后别忘了:
确保你的AppModule(或者对应的FeatureModule)里已经导入了TextMaskModule,并且声明了这个DateMaskDirective:
import { NgModule } from '@angular/core'; import { TextMaskModule } from 'angular2-text-mask'; import { DateMaskDirective } from './path/to/date-mask.directive'; // ...其他导入 @NgModule({ imports: [ TextMaskModule, // ...其他模块 ], declarations: [ DateMaskDirective, // ...其他组件/指令 ] }) export class AppModule { }
这样你的所有带matDatepicker的输入框就会自动应用法国日期格式的掩码了,不需要每个输入框都手动配置textMask属性~
内容的提问来源于stack exchange,提问作者Sébastien
相关产品推荐
相关产品推荐

