Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 307
Ahmed Abdelghany Avatar asked Nov 19 '25 20:11

Ahmed Abdelghany


1 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'];
  }
}
like image 134
Jasdeep Singh Avatar answered Nov 22 '25 16:11

Jasdeep Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!