问题
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