我正在构建一个 Ionic 应用程序,目前正在从 Ionic 3 迁移到 4。我有一些代码在 Ionic 3 中完美运行,但在 4 中则不然。 基本上,我似乎无法在输入字段中将数据与 [(ngModel(] 绑定。我已经导入了FormsModule
并将其添加到我的app.module.ts
中的导入中。以下是我的-component.ts
文件的外观:
export class SomeComponent implements OnInit {
someString: string = "test";
...
}
还有我的-component.html
<ion-input type="text" [(ngModel)]="someString"></ion-input>
{{someString}}
现在在我的应用程序中,{{someString}}
正确地显示"测试"。但是,更改输入的值不会以任何方式影响someString
变量。我可能缺少什么?
注意:这是一种解决方法,而不是解决方案。在下面查看我的编辑
奇怪的是,Ionic 4输入文档没有提到ngModel
,而是谈到了value
属性。所以我想,我会用[value]
替换[(ngModel)]
.
<ion-input type="text" [value]="someString"></ion-input>
为了能够在我的-component.ts
文件中访问该值,我执行以下操作:
-组件.html
<ion-input type="text" [value]="someString" (input)="do_something($event)"></ion-input>
-component.ts
do_something($event) {
this.someString = $event.target.value;
}
编辑
在使用上述解决方案之前,请确保您使用的是[(ngModel)]
而不是[ngModel]
。与我的问题相反,[(ngModel)]
确实有效。我宁愿使用[ngModel]
我只是在为同样的问题而苦苦挣扎,但找到了为什么 [(ngModel(] 在 Ionic 4 中不起作用的解决方案。
首先,您需要在app.module中导入CommonModule。还有一件事是将组件添加到 app.module 声明中。
@NgModule({
declarations: [AppComponent,
YourComponents],
entryComponents: [],
imports: [BrowserModule,
CommonModule,
FormsModule,
IonicModule.forRoot(),
AppRoutingModule
],
providers: [SystemSettingsProviderService,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent],
})
export class AppModule {}
从现在开始,ngModel,ngIfs/Fors工作得很好。