Ionic 4 - Two way binding [(ngModel)]

落爺英雄遲暮 提交于 2021-01-28 22:01:19

问题


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!


回答1:


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.




回答2:


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)
  }


来源:https://stackoverflow.com/questions/56938779/ionic-4-two-way-binding-ngmodel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!