美文网首页
angular7项目中开箱即用的指令

angular7项目中开箱即用的指令

作者: luckyvip | 来源:发表于2020-12-05 15:18 被阅读0次

    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 = '';
        }
      }
    }
    
    

    相关文章

      网友评论

          本文标题:angular7项目中开箱即用的指令

          本文链接:https://www.haomeiwen.com/subject/gosgwktx.html