Search code examples
angulartypescriptangular-formsngmodel

Why ngModel is not changing value of a string in angular?


the following is the template for a component:

<form>
    <label>Id: </label>
    <input type="text" [(ngModel)]="t" (keyup.enter)="Up()">
    <label for="pass">Password: </label>
    <input type="password" id="pass">
</form>

this is the ts file for the same component:

import { Component } from '@angular/core';

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.scss']
})
export class LoginComponent {
    t:string='';

    Up(){
        console.log(this.t);
    }
}

this is the app.module.ts file:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';

@NgModule({
    declarations: [
        AppComponent,
        LoginComponent
    ],
    imports: [
        BrowserModule,
        AppRoutingModule,
        FormsModule
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule { }

Whenever I run it and enter something in the textfield and press enter. it prints an empty string. I have added FormsModule in the app module. Why is the t variable not changing value?

I tried making it t!:string but that didn't work either.


Solution

  • I made a StackBlitz you can view here. When you run that it gives an error message:

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

    So that means you need to do one of the two things it suggests there. I chose to remove the <form> tag and now when I type something and press enter it logs it to the console as expected. Here's a final StackBlitz with it working