[英]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
当我尝试在模板上添加输入字段时,我得到此错误
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... 我不知道我错过了什么,angular2和打字稿对我来说是新的,如果有人能看到问题......
It doesn't look like you ever assign anything to newUser
class member. 看起来你没有为
newUser
类成员分配任何东西。
The error in trigger in the line [(ngModel)]="newUser.name"
. 行
[(ngModel)]="newUser.name"
中的触发错误。
You try to get name
from undefined
. 你试图从
undefined
得到name
。 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
您需要先使用
newUser
来执行newUser.name
You can intiliaze like 你可以像intiliaze一样
newUser: User = new User();
and change the User class as by adding a Constructor 并通过添加构造函数来更改User类
export class User{
constructor(
public name?: string,
public lastName?: string
) { }
}
Hope this will help 希望这会有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.