Reputation: 864
I am very new to angular. I define a model that export some fields. Before I had all the object of user written in my ts file. Now after I create model I am getting error:
ERROR TypeError: Cannot read property 'name' of undefined
How can I fix this error?
These are my codes.
export class User {
name: string = '';
email: string = '';
password: any = '';
}
import { User } from '../../models/user.model';
export class RegisterComponent implements OnInit {
public form: User;
}
<form #signupForm=ngForm (ngSubmit)="onSubmit()">
<input type="text" name="name" #name="ngModel" [(ngModel)]="form.name" class="form-control" id="inputname3" placeholder="Enter Name" required>
Upvotes: 0
Views: 649
Reputation: 11243
Just initialize your form
object before you use it.
Working copy is here https://stackblitz.com/edit/angular-xn211g
Upvotes: 0
Reputation: 501
register.component.ts
import { User } from '../../models/user.model';
export class RegisterComponent implements OnInit {
public form: User = {};
}
Please try this.
Upvotes: 1
Reputation: 4197
What I would do, is create an interface
UserRef
for type checking
user.ts
export interface UserRef {
name: string;
email: string;
password: any;
}
register.component.ts
import { UserRef } from '../../contracts/user';
import { User } from '../../models/user.model';
export class RegisterComponent implements OnInit {
public form: FormGroup;
public user: UserRef;
ngOnInit() {
this.user = new User()
// form setup
// this.form = ...
}
}
user.model.ts should look like
export class User {
name: string = '';
email: string = '';
password: any = '';
constructor() {}
}
Upvotes: 0
Reputation: 222702
You need to create an instance of the User ,
public form: User;
constructor(){
this.form = new User();
}
Upvotes: 1