在Angular 9中,可以使用自定义指令来去除输入框中的空格。下面是一个示例解决方法:
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appRemoveSpaces]'
})
export class RemoveSpacesDirective {
constructor(private el: ElementRef) { }
@HostListener('input', ['$event']) onInputChange(event) {
const value = this.el.nativeElement.value;
this.el.nativeElement.value = value.replace(/\s/g, '');
}
}
import { NgModule } from '@angular/core';
import { RemoveSpacesDirective } from './remove-spaces.directive';
@NgModule({
declarations: [
RemoveSpacesDirective
],
exports: [
RemoveSpacesDirective
]
})
export class SharedModule { }
import { SharedModule } from './shared/shared.module';
@NgModule({
imports: [
SharedModule
],
...
})
export class AppModule { }
现在,当用户在输入框中输入内容时,所有的空格都会被移除。