Reputation: 399
Trying to follow this example of hooking up a form from the Angular 2 tutorials. I'm adapting the code for a login page. https://angular.io/docs/ts/latest/guide/forms.html
Here is my model,
export class LoginModel {
constructor(
public id: number,
public password: string
) {}
}
Here is my component,
import { Component, OnInit } from "@angular/core";
import { LoginModel } from "../Models/login.model";
@Component({
selector: "login-form",
templateUrl: "views/login.component.html",
})
export class LoginComponent implements OnInit {
model = new LoginModel(111, "true");
submitted = false;
ngOnInit() {
this.model.id = 111;
this.model.password = "true";
}
onSubmit(): void {
this.submitted = true;
}
// remove - used for debugging
get diagnostic(): string {
return "HERE: " + JSON.stringify(this.model);
}
}
OnInit in the component is probably not needed, just thought I would give it a try.
Finally here is my HTML,
<div class="container">
<h1>Login Form</h1>
{{diagnostic}}
<form *ngIf="model">
<div class="form-group col-md-6">
<label for="id">User ID:</label>
<input type="text" class="form-control" id="id" name="id"
required
[(ngModel)]="model.id"
>
</div>
<div class="form-group col-md-6">
<label for="password">Password</label>
<input type="text" class="form-control" id="password" name="password"
required
[(ngModel)]="model.password"
>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
The error I keep running into is that "model.id" is undefined. To verify this I added *ngIf="model". I'm not sure why the model is showing as undefined here when it is defined in the LoginComponent which is imported through my module.
Any help would be greatly appreciated I've been stuck on this bit for a while and haven't been able to find anything helpful scouring the web.
Upvotes: 1
Views: 407
Reputation: 391
We don't have all the code, but I think you may not have all the necessary modules imported. Seems like you are missing FormsModule
and ReactiveFormsModule
Here is a plunker I created from the code you supplied above and I filled in the blanks for the missing NgModule
definition: Plunker
Upvotes: 1