angularionic-framework

ionic and angular ngModel not working undefined


I'm trying this on ionic + angular:

login-component.html:

<ion-content [fullscreen]="true">
  <div>
    <div style="margin-left:10%; margin-right:10%; margin-top: 5%;">
      <ion-input [(ngModel)]="username" placeholder="Nombre de usuario"></ion-input>
      <br>
      
      {{username}}
      
      <ion-input [(ngModel)]="password" type="password"  placeholder="Contraseña" ></ion-input>
    </div>
  </div>

  <div style="margin-left:10%; margin-right:10%; margin-top: 5%;">
    <ion-button (click)="login()">Acceder</ion-button>
    <ion-button>Cancelar</ion-button>
  </div>
</ion-content>

login-component.ts:

import { Component, OnInit } from '@angular/core';
import { AuthenticationLoginService } from 'authentication-login';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
})
export class LoginComponent implements OnInit {
  public username: string;
  public password: string;

  constructor(
    loginService: AuthenticationLoginService
  ) { }

  ngOnInit() {}

  async login() {
    alert(`hola ${this.username}!`);
  }
}

When I press the button it shows an alert saying hola undefined! If I do initialize the username with some data, its correctly shown in the {{username}} line, so it seems for some reason [(ngModel)] directive is not working. The browser console and the ionic serve command shows no error.

ionic info:

Ionic:

   Ionic CLI                     : 6.11.8 (/usr/lib/node_modules/@ionic/cli)
   Ionic Framework               : @ionic/angular 5.3.2
   @angular-devkit/build-angular : 0.1000.8
   @angular-devkit/schematics    : 10.0.8
   @angular/cli                  : 10.0.8
   @ionic/angular-toolkit        : 2.3.3

Capacitor:

   Capacitor CLI   : 2.4.1
   @capacitor/core : 2.4.1

Utility:

   cordova-res                          : not installed
   native-run (update available: 1.1.0) : 0.2.5

System:

   NodeJS : v14.10.1 (/usr/bin/node)
   npm    : 6.14.8
   OS     : Linux 4.19

Any ideas? thanks in advance.-

German


Solution

  • Solved. As @Pankaj Sati says, it is needed to add FormsModule and IonicModule to the module.ts file:

    import { NgModule } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { IonicModule } from '@ionic/angular';
    import { FormsModule } from '@angular/forms';
    
    import { AuthenticationRoutingModule } from './authentication-routing.module';
    
    import { LoginComponent } from './login/login.component';
    
    @NgModule({
      declarations: [
        LoginComponent
      ],
      imports: [
        CommonModule,
        AuthenticationRoutingModule,
        IonicModule,
        FormsModule,
      ]
    })
    export class AuthenticationModule { }
    

    After those changes, everything works like a charm. Cheers