Search code examples
angularangular2-templateangular2-formsangular2-services

Can not read property 'UserName' of undefined angular 2


I tried many solutions out there but none of them helped me to solve this ... Can't figure out what is the problem in my code ...

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">

COMPONENT CODE ::

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

                console.log(this.currentUser);

});

SERVICE ::

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 = "";

}


Solution

  • As you are using [(ngModel)] :

    You have to do it like this , you can't use safe operator ? with 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>
    

    OR

    Create intial object with default properties:

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

    Here is the link to the working demo of second method :

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