“[(ngModel)]”在 Ionic 4 中不具有约束力

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

我正在构建一个 Ionic 应用程序,目前正在从 Ionic 3 迁移到 Ionic 4。我有一些代码可以在 Ionic 3 中完美运行,但在 Ionic 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}} 正确显示 "test"。但是,更改输入值不会以任何方式影响 someString 变量。我可能缺少什么?

注意:这是一种解决方法,而不是解决方案。请参阅下面我的编辑

奇怪的是,Ionic 4 input documentation 没有提到 ngModel,而是提到了 value 属性。所以我想,我会用 [value].

替换 [(ngModel)]
<ion-input type="text" [value]="someString"></ion-input>

为了能够在我的 -component.ts 文件中访问该值,我做了如下操作:

-component.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 工作正常。