Attribute Directive on ion-input unable to get NgModel, but works with html input


#1

I’ve been trying desperately to applied restrictions and formatting as a user types input into an ion-input field

In the example here it simply converts all input immediately to uppercase.

The only problem is that as soon as I change the “input” tag for an “ion-input” it no longer works. The event just appears to do nothing.

Likewise in this example of injecting the NgModel from the input, then manipulating the model. It works in the example here

But as soon as I change the standard input for ion-input, then model is always null.

The end result is that I am trying to force uppercase on the field.

Almost about to resolve to working around angular altogether, and just getting the ref to the input element that is generated and working with straight JS.


#2

One way I think you can do this is by splitting up the binding like so:

<ion-input [ngModel]="shouting" (ngModelChange)="shout($event)"></ion-input>
@Page()
export class MyPage {
  shouting: string;

  shout(nv:string) {
    this.shouting = nv.toLocaleUpperCase();
  }
}

#3

Thanks. I’ll give it a go. I was trying to get it in an attribute directive, but I could just try making a new component. Might give me some new insights anyway :slight_smile:


#4

If I make it an attribute directive, then I end up with an endless loop

this.model.valueAccessor.writeValue(nv.toUpperCase());

Triggers ngModelChange, which then runs the function again, infinitely.

If I put an if block around it

if (this.model.value != nv.toUpperCase()) { this.model.valueAccessor.writeValue(nv.toUpperCase()); }

Then it still runs infinitely. It seems that one event fires immediately, and another on the next event loop so the method is continuously called with alternating values.

If I use the (input) event instead of onModelChange then it works for a standard input, but not an ion-input.

If I don’t use an attribute directive and update the model value directly, then it works!

Kinda frustrating, but better than where I was initially!

Also, I have no idea why NgModel wasn’t available in my initial attribute directive for an ion-input. I started another test from scratch and it works.

I’ve done another test with

if (this.model.value != nv.toUpperCase() && this.model.value != this.modelPreviousValue) { this.modelPreviousValue = this.model.value; this.model.valueAccessor.writeValue(nv.toUpperCase()); this.model.viewToModelUpdate(nv.toUpperCase()); }

Seems super hacky, and I wonder if there are going to be some subtle timing issues in there which could lead to irregular behaviour…

Anyway, it seems to work!

Now just to keep cursor position somehow…