简体   繁体   中英

Angular Custom Directive

I have more than 5 input text field to accept only comm/dot and only numbers .

[(ngModel)]="company.internetbill"
[(ngModel)]="company.electricitybill"
[(ngModel)]="company.waterbill"

etc..

I wrote a custom directive for the above validation. it works fine, My requirement is "when user input a -Comma- it must change decimal(dot).

 commtodecimal(ref:any){
        if(ref.includes(",")){
        ref=ref.replace(",",".")
        this.user.internetbill=ref
  }

is it possible to change the ngModel value in the same custom directive. so that i can use same directive for both features.

My Custom Directive is--

private regex: RegExp = new RegExp(/^[+-]?\d*[\.\,]?\d{0,8}$/g);
  private specialKeys: Array<string> = ['Backspace','ArrowLeft','ArrowRight','Delete'];
  constructor(private el:ElementRef) { }
  @HostListener('keydown',['$event'])onKeyDown(event:KeyboardEvent){
    if (this.specialKeys.indexOf(event.key) !== -1) {
      return;
    }
   const inputValue=this.el.nativeElement.value.concat(event.key)
    if(inputValue && !String(inputValue).match(this.regex)){
     event.preventDefault();
   }
   return
  }

or please suggest any optimized way. so that can reuse the code

You can achieve this with a custom directive, I made a simple custom directive to achieve that so it becomes reusable for all your inputs across your application.

I would leave this directive only for this work, following single responsibility pattern, leaving out the regex and other logic if not needed.

Open this url to see the example in action and the code: https://stackblitz.com/edit/angular-replacecommabydot-directive-ngmodel?file=src/app/replace-comma-by-dot.directive.ts

Key point for the directive to be able to modify the ngModel is:

@Directive({
  selector: '[ngModel][replaceCommaByDot]', // use ngModel selector here
})
export class ReplaceCommaByDotDirective {
  @Output() ngModelChange = new EventEmitter(); // emit with the same output name

  @HostListener('input', ['$event.target.value'])
  onInputChange(value: string) {
    value = value.replace(',', '.');
    this.ngModelChange.emit(value); // here we emit and the input with the banana box will receive and set the value
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM