在Angular 8中,可以使用@HostListener装饰器和HostBinding装饰器来解决此问题。通过@HostListener装饰器,可以监听宿主元素的事件,并在事件触发时调用相应的方法。通过HostBinding装饰器,可以将属性绑定到宿主元素的属性上。
以下是一个示例,说明如何创建一个自定义指令,只接受数字输入,并在移动版Chrome浏览器中起作用:
首先,创建一个名为NumberOnlyDirective的自定义指令:
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appNumberOnly]'
})
export class NumberOnlyDirective {
constructor(private el: ElementRef) { }
@HostListener('input', ['$event']) onInputChange(event) {
const initialValue = this.el.nativeElement.value;
this.el.nativeElement.value = initialValue.replace(/[^0-9]*/g, '');
if (initialValue !== this.el.nativeElement.value) {
event.stopPropagation();
}
}
}
然后,在你想要使用该自定义指令的组件中,导入并声明NumberOnlyDirective:
import { NumberOnlyDirective } from './number-only.directive';
@Component({
selector: 'app-my-component',
template: `
`,
directives: [NumberOnlyDirective]
})
export class MyComponent {}
最后,确保在移动版Chrome浏览器中也能起作用,你需要在polyfills.ts文件中添加以下代码,以确保支持所有浏览器的标准事件:
import 'zone.js/dist/zone';
import 'core-js/es/reflect';
import 'core-js/proposals/reflect-metadata';
import 'classlist.js';
import 'web-animations-js';
import 'intl';
import 'intl/locale-data/jsonp/en';
这样,你就可以在Angular 8中创建一个只接受数字的自定义指令,并确保在桌面浏览器和移动版Chrome浏览器中都能正常工作了。