1

Is there an easy way to set the value of an input blank/empty if the value equals zero (0)? I came across this AngularJS question here, Hide Value in input when it's zero in angular Js, but couldn't find anything for Angular 2+.

It would only need to be done on load of the page. I realize I could use a setter in the component, but wondering if there is something that could be put on the input itself.

Could this be done with a directive?

Ryan Buening
  • 1,399
  • 1
  • 18
  • 50

2 Answers2

1

You could use a template variable.

checkInputValue(input) {
  input.value = input.value == '0' ? '' : input.value;
}

and then

<input #input (keyup)="checkInputValue(input)" />

Edit for onload :

import { ViewChild, ElementRef, AfterViewInit } from '@angular/core'

// ...

export class Component implements AfterViewInit {

  @ViewChild('input') input: ElementRef

  ngAfterViewInit() {
    let inputValue = this.input.nativeElement.value;
    inputValue = inputValue == '0' ? '' : inputValue;
  }
}
filipbarak
  • 1,729
  • 1
  • 15
  • 28
  • I'm looking for something that can be done onload of the page. I edited my question. – Ryan Buening Feb 07 '18 at 14:53
  • Thanks. Your example does work. Do you know if a directive or property could be put directly on the input in the `component.html` rather than having logic inside the `component.ts`? – Ryan Buening Feb 07 '18 at 18:10
  • Hmm, I haven't tested this but you could try with the value attribute directive `` – filipbarak Feb 08 '18 at 07:54
0

If you want it done on page load, you could do this:

<input type="number" (ngModelChange)="data = $event === 0 ? '' : $event" [ngModel]="data" >

This will prevent the value from ever being 0, regardless of when.

David Anthony Acosta
  • 4,546
  • 1
  • 16
  • 18