Reputation: 465
I am using Angular 10 and trying to bind elements of my login form to the view model, but it does not seem to be updating. It stays at the default initial value. What am I doing wrong?
login.component.html
<div>
<form #loginData="ngForm" (submit)="doLogin()">
<input type="text" [(ngModel)]="loginData.Username" [ngModelOptions]="{standalone: true}">
<input type="password" [(ngModel)]="loginData.Password" [ngModelOptions]="{standalone: true}">
<button type="submit">Sign In</button>
</form>
</div>
login.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
constructor() { }
loginData: any = {
Username: "abcd",
Password: "1234"
}
ngOnInit(): void {
}
doLogin(): void {
console.log(this.loginData); //prints { Username: "abcd", Password: "1234"} every time
}
}
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
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 { }
Upvotes: 0
Views: 196
Reputation: 458
Change the name of your template variable for your form, it's conflicting with your loginData
variable in your component.
Here's a StackBlitz showing it working.
Upvotes: 2
Reputation: 526
You have your default value as: Username: "abcd", Password: "1234" This will always push those values. What you have to do is this:
loginData: any = {
Username: "",
Password: ""
}
Upvotes: 0