error : Cannot set property 'id' of undefined at UserComponent

Viewed 1494

I got the following error: Cannot set property 'id' of undefined at UserComponent.push../src/app/users/user/user.component.ts.UserComponent

TS Code

import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";

@Component({
  selector: "app-user",
  templateUrl: "./user.component.html",
  styleUrls: ["./user.component.css"],
})
export class UserComponent implements OnInit {
  user: { id: number; name: string };

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.user.id = +this.route.snapshot.params['id'];
  }
}

Template:

<p>User with ID {{user.id}} loaded.</p>
<p>User name is {{user.name}}</p>
2 Answers

As you have not initialized your user component property that is the reason of the error. So in your scenario, the user value is undefined.

You can use the safe navigation operation in template to fix this. It will render your UI without giving any errors even when your value is undefined or null.

<p>User with ID {{user?.id}} loaded.</p>
<p>User name is {{user?.name}}</p>

The other way would be initializing the values with default value.

export class UserComponent implements OnInit {
 // Assign the values with default values of corresponding(string in this case) types.
  user: { id: number, name: string } = {id: '', name: ''};

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.user.id = +this.route.snapshot.params['id'];
  }
}

You create user object but as undefined. So you have two solution.

First way is that in costructor initialize user

constructor(){
   this.user={id:null,name:null};  
}

Second way is that in html make self assign {{user?.id}}

Related