无法读取属性' UserName'未定义的角度2

时间:2017-11-03 05:50:53

标签: angular angular2-template angular2-forms angular2-services

我尝试了很多解决方案,但没有一个能帮助我解决这个问题...... 无法弄清楚我的代码中的问题是什么......

HTML CODE ::

<input type="text" class="form-control"  placeholder="Please Enter Your Username" [(ngModel)]="currentUser.UserName" minlength="3" required id="userNameBox" name="UserName" #uName="ngModel">

组件代码::

    profile() {
        let uid = Number(sessionStorage.getItem('id'));
        this._homeService.profile(uid).subscribe(
            res => {
            this.currentUser = res

                console.log(this.currentUser);

});

服务::

profile(id: number) {

        return this._http.get(url, id).map(
            (res: Response) => {
                console.log(res.json())
                return new User(res.json()

                ) }
        ).catch(this.handleError);
    }

MODEL ::

export class User {

constructor(json: any) {
    if (json != null) {
        this.Id = json.Id;
        this.UserName = json.UserName;
        this.FirstName = json.FirstName;
        this.LastName = json.LastName;
        this.Gender = json.Gender;
        this.Password = json.Password;
        this.Email = json.Email;
    }

}

Id: number = 0;
UserName: string = "";
FirstName: string = "";
LastName: string = "";
Gender: string = "";
Password: string = "";
Email: string = "";

}

1 个答案:

答案 0 :(得分:4)

正在使用[(ngModel)]

您必须这样做,您无法使用 safe operator ?2 way data binding

<div *ngIf="currentUser.UserName">
     <input type="text" class="form-control"  placeholder="Please Enter Your Username" [(ngModel)]="currentUser.UserName" minlength="3" required id="userNameBox" name="UserName" #uName="ngModel">
</div>

使用默认属性创建初始对象:

this.currentUser = { 
                        'UserName' : '',
                        'Email' : '',
                        // other properties , that you are using on template side 
                    }

以下是第二种方法的工作演示的链接:

https://stackblitz.com/edit/angular-initial-value