Search code examples
angularangular-router

Angular 15 this.router.navigate is not a function, this.router.navigateByUrl is NOT a function


This is a quick question:

Here's my code...

import { DOCUMENT } from '@angular/common';
import { Component, HostListener, Inject, NgZone } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-my-dashboards',
  templateUrl: './my-dashboards.component.html',
  styleUrls: ['./my-dashboards.component.css']
})
export class MyDashboardsComponent {
  @HostListener('click')
  breadcrumb: any;
  lawgroup: string;

  constructor(
    @Inject(DOCUMENT)
    private router: Router,
    private ngZone: NgZone
  ) {

  }

  ngOnInit() {
    this.breadcrumb = {
      'mainlabel': 'Law Groups',
      'links': [
        {
          'name': 'Home',
          'isLink': true,
          'link': '/dashboard/sales'
        },
        {
          'name': 'Law Groups Dashboard',
          'isLink': false,
          'link': '#'
        },
      ]
    };
  }

  goToLawGroupDashboard(lg: string): void {

    let fullRoute = '';
    this.lawgroup = lg;

    fullRoute = 'office/' + this.lawgroup;

    this.ngZone.run(() => {
      this.router.navigate([fullRoute]);
    });

  }

}

here's my HTML

<a [routerLink]="['/office', 'ABC']" class="h3adjust h3adjust-link" (click)="goToLawGroupDashboard('ABC')" title="Click to go to the ABC Dashboard">BLG</a>

No matter what I do... I keep getting the same error. WHY?

ERROR TypeError: this.router.navigate is not a function at my-dashboards.component.ts:50:19 at _ZoneDelegate.invoke (zone.js:375:26) at Object.onInvoke (core.mjs:24210:33) at _ZoneDelegate.invoke (zone.js:374:52)

I just don't understand. It works in an Angular 14 app I have but not in 15.

I just want to pass this "ABC" in the URL and yet, router.navigate() is not a function?

UPDATE:

Removing @Inject (DOCUMENT) took away the error but here's my loadchildren router....

But it goes nowhere. D'oh!

      {
        path: 'office/:id',
        component: OfficeComponent
      }

Solution

  • Nah, It couldn't have worked on v14.

    This line is very wrong : @Inject(DOCUMENT) private router: Router

    You'll get the Document instead of the Router. Remove the

    @Inject(DOCUMENT) and you should be fine !