Search code examples
javascriptangularangular2-routing

Cannot read property 'id' of undefined while navigate to route with ID in Angular


I am unable to navigate to a route with ID argument when using the router.

My code is below:

app-routing.module.ts:

const routes: Routes = [
  {path:"departments", component:DepartmentsComponent},
  {path:"departments/:id", component:DepartmentsDetailsComponent}
];

Departments.components.html:

<ul class="items">
    <li (click)="onSelect(depart)" *ngFor="let dept of departmentsList">
        <span class="badge">{{ dept.id }}</span> {{ dept.department }}
    </li>
</ul>

Departments.components.ts:

export class DepartmentsComponent implements OnInit {

  departmentsList = [
    { "id":1, "department": "Angular" },
    { "id":2, "department": "React Js" },
    { "id":3, "department": "Node Js" },
    { "id":4, "department": "Express Js" },
    { "id":5, "department": "MOngo DB" }
  ];

  constructor(private router: Router) { }

  ngOnInit() {
  }

  onSelect(depart){
    this.router.navigate(['/departments',depart.id]);
  }

}

leads to an error:

ERROR: TypeError: **Cannot read property 'id' of undefined**

       at DepartmentsComponent.onSelect (departments.component.ts:25)
       at Object.eval [as handleEvent] (DepartmentsComponent.html:3)
       at handleEvent (core.js:38098)
       at callWithDebugContext (core.js:39716)
       at Object.debugHandleEvent [as handleEvent] (core.js:39352)
       at dispatchEvent (core.js:25818)
       at core.js:37030
       at HTMLLIElement.<anonymous> (platform-browser.js:1789)
       at ZoneDelegate.invokeTask (zone-evergreen.js:391)
       at Object.onInvokeTask (core.js:34182)

Solution

  • It is happening because you are passing depart in onSelect(depart) which is undefined. The right value to pass is dept which is derived from *ngFor.

    Change

    <ul class="items">
        <li (click)="onSelect(depart)" *ngFor="let dept of departmentsList">
            <span class="badge">{{ dept.id }}</span> {{ dept.department }}
        </li>
    </ul> 
    

    to

    <ul class="items">
        <li (click)="onSelect(dept)" *ngFor="let dept of departmentsList">
            <span class="badge">{{ dept.id }}</span> {{ dept.department }}
        </li>
    </ul>