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>
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'];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With