user1687891
user1687891

Reputation: 864

Cannot read property 'name' of undefined after creating a model

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.

user.model.ts

export class User {
    name: string = '';
    email: string = '';
    password: any = '';
}

register.component.ts

import { User } from '../../models/user.model';
export class RegisterComponent implements OnInit {
    public form: User;
}

register.html

<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

Answers (4)

Sunil
Sunil

Reputation: 11243

Just initialize your form object before you use it.

Working copy is here https://stackblitz.com/edit/angular-xn211g

Upvotes: 0

Bhavin
Bhavin

Reputation: 501

register.component.ts

import { User } from '../../models/user.model';
export class RegisterComponent implements OnInit {
   public form: User = {};
}

Please try this.

Upvotes: 1

mehany
mehany

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

Sajeetharan
Sajeetharan

Reputation: 222702

You need to create an instance of the User ,

 public form: User;

constructor(){
  this.form = new User();
}

Upvotes: 1

Related Questions