Warm tip: This article is reproduced from stackoverflow.com, please click
angular ionic-framework ionic4

"[(ngModel)]" not binding in Ionic 4

发布于 2020-04-08 09:32:05

I'm building an Ionic application, currently migrating from Ionic 3 to 4. I've got some code which works perfectly in Ionic 3, but not in 4. Basically, I can't seem to bind data with [(ngModel)] in an input field. I've imported FormsModule and added it among my imports in my app.module.ts. Here's how my -component.ts file looks like:

export class SomeComponent implements OnInit {
  someString: string = "test";
  ...
}

And my -component.html

<ion-input type="text" [(ngModel)]="someString"></ion-input>
{{someString}}

Now in my application, {{someString}} rightly shows "test". However, changing the value of the input doesn't affect the someString variable in any way. What could I be missing?

Questioner
che-azeh
Viewed
69
che-azeh 2020-02-01 11:42

Curiously, the Ionic 4 input documentation has no mention of ngModel, and rather talks of a value attribute. So I figured, I'd replace [(ngModel)] with [value].

<ion-input type="text" [value]="someString"></ion-input>

To be able to access that value in my -component.ts file, I do something like:

-component.html

<ion-input type="text" [value]="someString" (input)="do_something($event)"></ion-input>

-component.ts

do_something($event) {
  this.someString = $event.target.value;
}