Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 885
Cedric Ipkiss Avatar asked Jan 25 '26 04:01

Cedric Ipkiss


2 Answers

Note: This is a workaround, not the solution. See my edit below

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

EDIT

Before using the above solution, be certain you're using [(ngModel)] and not [ngModel]. Contrary to what my question stated, [(ngModel)] actually works. I was rather using [ngModel]

like image 165
Cedric Ipkiss Avatar answered Jan 29 '26 01:01

Cedric Ipkiss


I was just struggling with the same issue but found solution why [(ngModel)] was not working in Ionic 4 for me.

First of all, you need to have CommonModule imported in your app.module. One more thing is to add your component into app.module declarations.

@NgModule({
  declarations: [AppComponent,
                YourComponents],
  entryComponents: [],
  imports: [BrowserModule,
            CommonModule,
            FormsModule,
            IonicModule.forRoot(),
            AppRoutingModule
          ],
  providers: [SystemSettingsProviderService,
             { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}

From now on, ngModel, ngIfs/Fors are working just fine.

like image 44
Smokovsky Avatar answered Jan 29 '26 02:01

Smokovsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!