Simon
Simon

Reputation: 2538

Ionic 4 - Two way binding [(ngModel)]

I'm struggling to use two way binding in Ionic 4. I used to use Ionic 3 and two way binding was super easy, I'm not sure why I'm struggling.

In my app.module.ts I import:

import { FormsModule } from '@angular/forms';

imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule,
    RoundProgressModule,
    FormsModule,
    HttpClientModule
  ],

On my .ts file for my page, I simply init a variable:

user:any = { phone: '', name: '', date: '' }

and then I have a function I call to change the format of user.phone

formatNumber() {
    let num = this.user.phone;
    this.user.phone = new AsYouType('US').input(num) // a package to format numbers
    console.log(this.user.phone)
  }

the console.log produces the correct information, but it doesn't change in the input field..

My .html file looks like this:

 <form>
    <input class="phone-input" name="phone" type="text" placeholder="(123) 456-7890" (ngModelChange)="formatNumber()" [(ngModel)]="user.phone">
 </form>

To me, that seems like it should all work... What am I doing wrong? It doesn't seem very obvious to me.

Thanks!

Upvotes: 1

Views: 1590

Answers (2)

Eliseo
Eliseo

Reputation: 57909

the correct use [ngModel] (ngModelChange) must be like

<input class="phone-input" name="phone" type="text" placeholder="(123) 456-7890" 
    (ngModelChange)="formatNumber($event)" [ngModel]="user.phone">

See the $event as argument, and your function

formatNumber(num) { //<--see the argument
    this.user.phone = ....
    console.log(this.user.phone)
  }

Upvotes: 0

yashpatelyk
yashpatelyk

Reputation: 429

Try this,

<form>
    <input class="phone-input" name="phone" type="text" placeholder="(123) 456- 
    7890" (input)="formatNumber()" [(ngModel)]="user.phone">
</form>

input instead of ngModelChange.

Upvotes: 3

Related Questions