在我的文本区域中,我使用 onKeydown 事件来监听用户输入的字符。 我需要阻止 Alt gr + 键组合值(ē、r̥、ṭ、...)以避免文本区域中出现重音键。
if (event.code === 'AltRight') {
console.log('Prevent Accent letters');
event.preventDefault();
}
(or)
if (event.code === 17 || event.code === 18) {
console.log('Prevent Accent letters');
event.preventDefault();
}
没有任何作用。他们正在输入这些 if 条件,但重音文本仍然打印在我的文本区域中。如何防止这种情况发生
我们需要创建一个与正则表达式 `` 一起使用的自定义指令来否定所有替代代码字符,并且只过滤掉有效的字符,我们可以使用
match
来做到这一点!
指令
import { Directive, HostListener, Input } from '@angular/core';
@Directive({
selector: '[appPermit]',
standalone: true,
})
export class PermitDirective {
@Input('regex') pattern: RegExp = /[\\x00-\\x7F]*/i;
constructor() {}
@HostListener('input', ['$event']) onInput(e: any) {
e.target.value = this.isValidText(e, '');
}
@HostListener('paste', ['$event'])
onPaste(event: any) {
return this.isValidText(event, event.clipboardData.getData('text/plain'));
}
isValidText(e: any, text: any) {
debugger;
const [selectionStart, selectionEnd] = this.getSelectionRange(e.target);
// for elements not having value accessor(innerText)
const existingValue = e.target.value ?? e.target.innerText;
console.log(
e.target.value,
'typed',
existingValue.substring(0, selectionStart) +
text +
existingValue.substring(selectionEnd)
);
return (
existingValue.substring(0, selectionStart) +
text +
existingValue.substring(selectionEnd)
)
.match(this.pattern)
.toString();
}
getSelectionRange(el: HTMLElement) {
if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {
// These properties aren't present for any HTMLElement
return [el.selectionStart, el.selectionEnd];
}
// currently getSelection() doesn't work on the content of <textarea> and // <input> elements in Firefox, Edge (Legacy)
const { startOffset, endOffset } = <any>getSelection()?.getRangeAt(0);
return [startOffset, endOffset];
}
}
main.ts
import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
import { PermitDirective } from './app/input.directive';
@Component({
selector: 'app-root',
imports: [PermitDirective],
standalone: true,
template: `
<textarea appPermit></textarea>
`,
})
export class App {
name = 'Angular';
}
bootstrapApplication(App);