简体   繁体   中英

Upgrade directive from angular js to angular 8

someone can help to upgrade this directive to a angular 2+

I like this directive, cuz let me validate only float and too to copy paste the data or drop data in in it

var myApp = angular.module('myApp', ['ngStorage']);
myApp.controller('MyCtrl', ['$scope', function($scope) {

}]).directive('floatOnly', function() {
  return {
    require: 'ngModel',
    restrict: 'A',
    link: function(scope, element, attrs, modelCtrl) {
      modelCtrl.$parsers.push(function(inputValue) {
        if (inputValue === undefined) return '';

        // Remove forbidden characters
        cleanInputValue = inputValue.replace(',', '.') // change commas to dots
          .replace(/[^\d.]/g, '') // keep numbers and dots
          .replace(/\./, "x") // change the first dot in X
          .replace(/\./g, "") // remove all dots
          .replace(/x/, "."); // change X to dot
        if (cleanInputValue != inputValue) {
          modelCtrl.$setViewValue(cleanInputValue);
          modelCtrl.$render();
        }
        return cleanInputValue;
      });
    }
  }
});

jsfiddle example

Try this: WORKING DEMO

import { Directive, Renderer2, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[float-only]'
})
export class FloatOnlyDirective{
  constructor(private elem: ElementRef, private render: Renderer2) {  }
  @HostListener('input')
  onChange() {
    let value = this.elem.nativeElement.value.replace(',', '.') 
          .replace(/[^\d.]/g, '') // keep numbers and dots
          .replace(/\./, "x") // change the first dot in X
          .replace(/\./g, "") // remove all dots
          .replace(/x/, ".") ;
    this.elem.nativeElement.value = value;
  }

}

You can update the innerHtml by using Renderer2 also. That will be more cleaner,

All the Best for your Angular journey !!

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