1、去除input首尾的空格
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
import { FormGroup, FormControl, NgControl } from '@angular/forms';
@Directive({
// tslint:disable-next-line:directive-selector
selector: '[input-noSpace]'
})
export class InputNoSpaceDirective {
constructor(private elementRef: ElementRef, private control: NgControl) {
}
@HostListener('keydown', ['$event'])
keydownFun(evt) {
if (evt.key.trim() === '') {
evt.preventDefault();
}
}
@HostListener('keyup', ['$event', '$event.target'])
keyupFun(evt, target) {
if (target.value) {
this.control.control.setValue(target.value.replace(/(\s*)/g, ''));
}
}
}
2、input限制仅数字输入
import { Directive, ElementRef } from '@angular/core';
import { HostListener } from '@angular/core';
@Directive({
// tslint:disable-next-line:directive-selector
selector: '[input-number]'
})
export class NumberinputDirective {
constructor(element: ElementRef) {}
@HostListener('input', ['$event'])
onInput(event) {
const inputValNumber = /^[0-9]*$/;
if (inputValNumber.test(event.target.value) === false) {
event.target.value = '';
}
}
}
网友评论