Search code examples
javascriptangularangular2-directives

binding data in Angular 2


I'm learning angular-2 for a project and I've no idea about this error. This is my html file. I want to get values from these field. Any idea

 <form>
  <label> Name: </label><br />
  <input type="text" name="name"  [(ngModel)]= "user.name" /> <br/>
  <label> Id: </label><br/>
  <input type="number" name="Id"  [(ngModel)]= "user.Id"    /><br/>
  <label> Email: </label><br />
  <input type="text" name="email"  [(ngModel)]= "user.email" /><br/>
</form>

This is in my .ts file

   export class UserComponent{    
   user:User;  constructor(){ } }
     }
// interface
            interface User{
                name:string;
                Id:number;
                email:string;  }

I can't do something like {{user.name}} on my Html file. Why is that so ? Am I doing it wrong ?


Solution

  • May be because you didn't initialize the user variable as an object? Try this:

    export class UserComponent {    
      user: User = {
        name: "",
        Id: null,
        email: ""
      };
      constructor() { }
    }