我想创建Angular 2指令,它只会从用户输入到输入字段的文本的开头和结尾修剪空格。
我有输入字段
<input trim name="fruit" [(ngModel)]="fruit"/>
和指令
import {Directive, ElementRef} from "@angular/core";
@Directive({
selector: 'input[trim]',
host: {'(blur)': 'onChange($event)'}
})
export class TrimWhiteSpace {
constructor(private cdRef:ChangeDetectorRef, private el: ElementRef){}
onChange($event:any) {
let theEvent = $event || window.event;
theEvent.target.value = theEvent.target.value.trim();
}
}
哪个工作正常,删除空格并更改输入字段中的文本,但问题是ngModel变量“fruit”中的值没有更改,它仍然包含在开头或结尾处带空格的文本。
我还尝试在onChange方法中添加以下内容
this.el.nativeElement.value = theEvent.trim();
this.cdRef.detectChanges();
并将表单(模糊)更改为(ngModelChange),但ngModel中的文本不受影响。
有什么建议?
你看过https://github.com/anein/angular2-trim-directive吗?
似乎它会解决您的用例
避免混淆改变模型属性名称。
<input name="fruit" [(ngModel)]="fruit1" (change)="fruit1=fruit1.trim()"/>
虽然已经晚了一年多,但你可能想尝试https://www.npmjs.com/package/ngx-trim-directive
它取决于一个简单的事实,即Angular监听输入事件以使视图到模型绑定成为存在。
演示:https://angular-86w6nm.stackblitz.io,编辑:https://stackblitz.com/edit/angular-86w6nm
@ErVipinSharma我更改了文件src / input-trim.directive.ts,您可以在上面链接中找到github。在这个文件中我删除了方法
@HostListener( 'input', ['$event.type', '$event.target.value'] )
onInput( event: string, value: string ): void {
this.updateValue( event, value );
}
并添加了方法
@HostListener('paste', ['$event', '$event.target'])
onPaste($event: any, target: any) {
// do something when on paste event happens
}
最好使用fromEvent来防止冗余更改检测(将由@HostListener执行)。示例中的CommonController只是基类,它将onDestroy钩子中的主题从observable触发到unsubsribe。
@Directive({
selector: '[appTrimOnBlur]'
})
export class TrimOnBlurDirective extends CommonController implements OnInit {
constructor(private elementRef: ElementRef,
@Self() private ngControl: NgControl) {
super();
}
ngOnInit(): void {
fromEvent(this.elementRef.nativeElement, 'blur').pipe(
takeUntil(this.unsubscribeOnDestroy)
).subscribe(() => {
const currentValue: string = this.ngControl.value.toString();
const whitespace: string = ' ';
if (currentValue.startsWith(whitespace) || currentValue.endsWith(whitespace)) {
this.ngControl.control.patchValue(currentValue.trim());
}
});
}
}
您可以创建通用修剪指令,它不仅可以修复模糊事件,还可以修改任何您提供的修剪:
@Input() public trimEventName: string = 'blur';
constructor(private elementRef: ElementRef,
@Self() private ngControl: NgControl) {
super();
}
ngOnInit(): void {
fromEvent(this.elementRef.nativeElement, this.trimEventName).pipe(
takeUntil(this.unsubscribeOnDestroy)
).subscribe(() => {
const currentValue: string = this.ngControl.value.toString();
const whitespace: string = ' ';
if (currentValue.startsWith(whitespace) || currentValue.endsWith(whitespace)) {
this.ngControl.control.patchValue(currentValue.trim());
}
});
}