简体   繁体   中英

TypeError: self.context.newUser is undefined on Angular2

When I try to add an input filed on the template I get this errr TypeError: self.context.newUser is undefined

this is the component

import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { User } from './user';
import { UserService } from './user.service';


@Component({
  selector: 'vista3',
  templateUrl: 'app/vista3.component.html',
  styleUrls:['app/vista3.component.css']
})

export class Vista3Component implements OnInit{
  users: User[] = [];
  newUser: User;

  constructor(
    private router: Router,
    private userService: UserService) {
  }

  ngOnInit(){
    this.userService.getUsers().then( users => this.users = users);
  }
}

the template

<div  class="separar">
  <table class="table table-striped">
      <tr>
        <th>Nombre</th>
        <th>Apellido</th>
      </tr>
        <tr *ngFor="let user of users">
          <td>{{user.name}}</td><td>{{user.lastName}}</td>
        </tr>
  </table>
</div>
<div  class="separar">
  <div class="row">
    <div class="col-xs-12 col-md-3">
      Nombre: <input [(ngModel)]="newUser.name"/>
    </div>
  </div>
</div>

and the user class

export class User{
  name: string;
  lastName: string;
}

I don't know what I'm missing ,angular2 and typescript are new for me, if somebody cann see the problem...

  1. It doesn't look like you ever assign anything to newUser class member.

  2. The error in trigger in the line [(ngModel)]="newUser.name" .

You try to get name from undefined . I'd recommend using ?. operator.

<input [(ngModel)]="newUser?.name"/>

And also create an empty user in the constructor:

  constructor(
    private router: Router,
    private userService: UserService) {

    this.newUser = new User;
  }

You need to intiliaze newUser first in order to do newUser.name

You can intiliaze like

newUser: User = new User();

and change the User class as by adding a Constructor

export class User{
    constructor(
        public name?: string,
        public lastName?: string
    ) { }
}

Hope this will help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM