Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular NgModel not updating Typescript

I’ve been coding Angular for 5 years now and in a personal project my first interaction with [(ngModel)] is driving me insane and I don’t know why.
Two-way data bind should be easy and pretty straight forward. Still, this is not updating the Typescript variable. WHY is this happening? It always stays empty.

And yes, of course FormsModule is imported in app.modules

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-nav',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.scss']
})
export class NavComponent implements OnInit {

  username:string ="";
  passwd:string ="";
  constructor(private authService: AuthService) { }

  ngOnInit(): void {
  }

  $login(): void {
    alert(this.username);
    this.authService.login({ login: this.username, passwd: this.passwd })
      .subscribe(
        response => {
          console.log('Login bem-sucedido!', response);
        },
        error => {
          console.error('Erro durante o login:', error);
        }
      );
  }
}
                        <form class="px-5">
                            <div class="mb-3 py-3">
                                <label for="id-login">Login</label>
                                <input type="text" class="form-control" id="id-login" placeholder="Login" [(ngModel)]="username">
                                <label for="id-password" class="mt-3">Senha</label>
                                <input type="password" class="form-control "  id="id-passwd" placeholder="Senha" [(ngModel)]="passwd">
                                <button class="mt-3 btn btn-primary" (click)="$login()">Entrar</button>
                            </div>
                        </form>

NgModel always worked.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I implemented the code you shared and angular threw some errors on the console which gave me the ways to fix it!

ERROR Error: NG01352: If ngModel is used within a form tag, either the
name attribute must be set or the form control must be defined as
‘standalone’ in ngModelOptions.

Example 1: <input [(ngModel)]="person.firstName" name="first"> Example
2: <input [(ngModel)]="person.firstName"
[ngModelOptions]="{standalone: true}">

You can use either one of these fixes and solve your issue!

code main.ts

import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
import { AuthService } from './auth.service';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [FormsModule],
  template: `
     <form class="px-5">
          <div class="mb-3 py-3">
              <label for="id-login">Login</label>
              <input type="text" class="form-control" id="id-login" placeholder="Login" [(ngModel)]="username" name="username">
              <label for="id-password" class="mt-3">Senha</label>
              <input type="password" class="form-control "  id="id-passwd" placeholder="Senha" [(ngModel)]="passwd" [ngModelOptions]="{standalone: true}">
              <button class="mt-3 btn btn-primary" (click)="$login()">Entrar</button>
          </div>
      </form>
  `,
})
export class App {
  username: string = '';
  passwd: string = '';
  constructor(private authService: AuthService) {}

  ngOnInit(): void {}

  $login(): void {
    alert(this.username);
    this.authService
      .login({ login: this.username, passwd: this.passwd })
      .subscribe({
        next: (response) => {
          console.log('Login bem-sucedido!', response);
        },
        error: (error) => {
          console.error('Erro durante o login:', error);
        },
      });
  }
}

bootstrapApplication(App);

service.ts

import { Injectable } from '@angular/core';
import { of } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class AuthService {
  constructor() {}

  login(params: any) {
    console.log('params are', params);
    return of(true);
  }
}

stackblitz demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading