您要实现的基本上是屏蔽显示的值,就像<input type="password" 所做的那样。唯一的事情是由浏览器处理,因此从 JS/Angular 实现它可能会有点棘手。
但这仍然是可能的。请注意,由于您使用字符屏蔽数字,因此输入必须是 type="text",否则它将不接受被屏蔽的字符。你可以这样做:
maskInput.directive.ts
import { Directive, Input, OnInit, ElementRef, EventEmitter, Output } from '@angular/core';
@Directive({
selector: '[maskInput]'
})
export class MaskInputDirective implements OnInit {
readonly TransformTable = {
0: 'o',
1: 'a',
2: 'b',
3: 'c',
4: 'd',
5: 'e',
6: 'f',
7: 'g',
8: 'h',
9: 'i'
};
@Input() maskInput: any;
@Output() maskInputChange = new EventEmitter();
constructor(
private el: ElementRef
) {
}
ngOnInit(): void {
const elem = this.el.nativeElement;
elem.addEventListener('keydown', (e) => {
elem.value += this.TransformTable[e.key];
// just for good measure
if (this.maskInput === null || this.maskInput === undefined) {
this.maskInput = '';
}
this.maskInputChange.emit(this.maskInput += e.key);
e.preventDefault();
return false;
});
}
}
test.component.ts
export class TestComponent {
actualValue: any;
}
test.component.html
<input type="text" [(maskInput)]="actualValue">
<div>Original value: {{actualValue}}</div>
工作解决方案:https://stackblitz.com/edit/angular-ivy-isjziu?file=src%2Fapp%2FmaskInput.directive.ts