Ion-input not working with directives but regular input does


#1

Note, I’m new at this an making lots of mistakes but…

Working on a directive, “numbers-only”, that checks for valid numbers and changes background from red to green.

sort of works for angular 2 but must specify color as red, green, not ionic primary, secondary, danger, etc

<input numbers-only (blur)=“evaluateEarnings()” [(ngModel)]=“meeting.earnings” type=“text” [disabled]=“meeting.dollarsPerHrDisabled”>

but this does not.

{{earningsLabel}}

Directive code snippet:

@HostListener(‘keyup’, [’$event’])
keyup(e: KeyboardEvent) {
console.log("Key Up! " + e.key);
// }
// @HostListener(‘keypress’, [’$event’])
// keyPress() {
console.log(“In numbers-only directive: keypress”);
if(isNaN(this.el.nativeElement.value.replace(/,/gi, “”))){
//this.el.nativeElement.style.backgroundColor = “danger”;
this.el.nativeElement.style.backgroundColor = “red”;
}else{
this.el.nativeElement.style.backgroundColor = “green”;
}
}

I get error:

error_handler.js:48 EXCEPTION: Error in ./CalcPage class CalcPage - inline template:54:16 caused by: Cannot read property ‘replace’ of undefined
which is from:
if(isNaN(this.el.nativeElement.value.replace(/,/gi, “”)))


#2

For some reason my html code disappeared: here is working and not working.

Working

            <input numbers-only (blur)="evaluateEarnings()" [(ngModel)]="meeting.earnings" type="text" [disabled]="meeting.dollarsPerHrDisabled">

Not Working:

{{earningsLabel}}

#3

Is there a reason you’re not just using Angular’s standard validation features?


#4
            <ion-input numbers-only (blur)="evaluateEarnings()" [(ngModel)]="meeting.earnings" type="text" [disabled]="meeting.dollarsPerHrDisabled"></ion-input>

#5

I want decimal number input but type = “number” provides non-decimal input. Tried virtual keyboard, but don’t like the look. Use type=“tel” gives keyboard with decimal on symbol page. Not necessarily what I want. type=“text” provides full keyboard, but need to make sure the input is a valid number. Since I do this in two places, I thought a directive may be better than duplicating code - particularly since it forces me to learn how to implement directives.

Right now, I am leaning toward testing on “blur” in the page.ts code upon leaving the ion-input element and using the “teL” keyboard. I have that working, but thought a directive may be the more correct place to do this for code reuseability.