我的同事带着指令来了:
https://stackblitz.com/edit/angular-jrf1jn
import { Directive, HostListener, Input, OnInit, OnDestroy } from '@angular/core';
import { NgModel } from '@angular/forms';
import { Subject, pipe } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@Directive({
selector: '[appPdMask][ngModel]'
})
export class PdInputMaskDirective implements OnInit, OnDestroy {
@Input() appPdMask = 'time';
constructor (
public model: NgModel,
) {}
private _unsubscribeAll = new Subject<void>();
ngOnInit() {
this.model.valueChanges
.pipe(
takeUntil(this._unsubscribeAll)
)
.subscribe(val => {
const newVal = this._parseValue(val);
this.model.valueAccessor.writeValue(newVal);
});
}
ngOnDestroy() {
this._unsubscribeAll.next();
this._unsubscribeAll.complete();
}
private _parseValue( v ) {
const x = v.replace(/\D/g, '').match(/(\d{0,2})(\d{0,2})/);
return !x[2] ? x[1] : x[1] + ':' + x[2];
}
}
现在一切如期而至:)非常感谢@seyd:clap: