Search code examples
angularangular-directive

How to change the view value in Angular?


I created a attribute directive for a percentage field to make it possible to handle decimals. I want to disable adding decimals to the input field. It works. But the backend adds ,00 to the value after blur and I want to remove the ,00 added by the backend.

Input field:

<input type="text"
#formItem
[name]="id"
[id]="id"
class="form-control"
[ngModel]="value"
(blur)="change.emit(formItem.value)"
removeDecimals="true" />

Directive:

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

@Directive({
  selector: '[removeDecimals]'
})

export class RemoveDecimalsDirective implements OnInit {
  @Input() removeDecimals: boolean | undefined;
  private _value : any;
  
  constructor(private el: ElementRef, private renderer2: Renderer2) {
  }

  ngOnInit() {
  }
  
  @HostListener('input') onChange() {
    if(this.removeDecimals) {
      const { value } = this.el.nativeElement;
      this.renderer2.setProperty(this.el.nativeElement, 'value', value.replace(/[^0-9]/g, ''));
    }
  }
}

So tried to add something like this to the directive, to remove the ,00 from the view but it didn't work.

@HostListener('blur') onBlur() {
    let formatValue = this.el.nativeElement.value;

    const index = formatValue.indexOf(',');
    if (index > -1) {
        formatValue = this.el.nativeElement.value.slice(0, index);
    }

    this.renderer2.setProperty(this.el.nativeElement, 'value', formatValue);
}

So when I enter a value on the input fields, it is not possible to add decimals, only numbers which is correct. But when I leave the field, it adds ,00 from the backend.

How to Remove the ,00 which is added from the backend after blur to the input field?


Solution

  • DEMO u can use custom pipe for your model

    [ngModel]="value | num"
    

    your custom pipe

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
      name: 'num'
    })
    export class SafePipe implements PipeTransform {
    
     
     public transform(value: any) {
        return value.split(",")[0]
      }
    }