在Angular 2中输入具有不同显示文本和值的文本元素

时间:2018-01-18 11:22:05

标签: html css angular

我有一个用例,其中有一个输入文本元素,如果一个人输入2345它应该显示为2,345但在后端它应该将数字存储为2345.我们怎么能在Angular 2中实现这个?

3 个答案:

答案 0 :(得分:2)

对数字使用角度内置过滤管道将https://docs.angularjs.org/api/ng/filter/number

{{1234 | number}}

输出

1,234

答案 1 :(得分:0)

你可以制作一个使用@HotListener模糊和聚焦的指令

@Directive({ selector: "[app-number]" })
export class NumberFormat implements OnInit {

  private el: HTMLInputElement;
  constructor(private elementRef: ElementRef) {
    this.el = this.elementRef.nativeElement;
  }

  ngOnInit() {
    this.el.value = this.transform(this.el.value);
  }

  @HostListener("focus", ["$event.target.value"])
  onFocus(value) {
    this.el.value = this.parse(value); // opossite of transform
  }

  @HostListener("blur", ["$event.target.value"])
  onBlur(value) {
    this.el.value = this.transform(value);
  }

  //value --> value formatted
  transform(value:any) 
  {
     ...return your value formated...
  }
  //value formated--> value 
  parse(valueFormated:any){
      ..return the real value....
  }

答案 2 :(得分:-1)

希望this会很有用:

的index.html:

<body ng-app="numberFilterExample">
  <script>
  angular.module('numberFilterExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
      $scope.val = 1234.56789;
    }]);
</script>
<div ng-controller="ExampleController">
  <label>Enter number: <input ng-model='val'></label><br>
  Default formatting: <span id='number-default'>{{val | number}}</span><br>
  No fractions: <span>{{val | number:0}}</span><br>
  Negative number: <span>{{-val | number:4}}</span>
</div>
</body>
</html>

Protractor.js

 it('should format numbers', function() {
   expect(element(by.id('number-default')).getText()).toBe('1,234.568');
   expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
   expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
 });

 it('should update', function() {
   element(by.model('val')).clear();
   element(by.model('val')).sendKeys('3374.333');
   expect(element(by.id('number-default')).getText()).toBe('3,374.333');
   expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
   expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
});