skip to Main Content

I have a function using location

ts file


  isHomePage() {
    return location.pathname == '/';
  }

css file

<a routerLink="/" [ngClass]="{'current-active':isHomePage()}" class="nav-link " aria-current="page">Home</a>

It is working at browser but i have an error at Angular cli

ERROR ReferenceError: location is not defined

My tsconfig.json file


{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "strict": true,
    "noImplicitOverride": true,
    "noPropertyAccessFromIndexSignature": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "skipLibCheck": true,
    "isolatedModules": true,
    "esModuleInterop": true,
    "sourceMap": true,
    "declaration": false,
    "experimentalDecorators": true,
    "moduleResolution": "bundler",
    "importHelpers": true,
    "target": "ES2022",
    "module": "ES2022",
    "lib": [
      "ES2022",
      "dom"
    ]
  },
  "angularCompilerOptions": {
    "enableI18nLegacyMessageIdFormat": false,
    "strictInjectionParameters": true,
    "strictInputAccessModifiers": true,
    "strictTemplates": true
  }
}

2

Answers


  1. Chosen as BEST ANSWER

    Well i couldn't fix location is not defined error but instead of that i used router service, code below

        export class HeaderComponent implements OnInit {
    
      constructor(private router: Router)
      {
    
      }
      ngOnInit(): void {
       
      }
      isHomePage(): boolean {
    
        return this.router.url === '/';
      }
    
    }
    

  2. It’s difficult to tell the answer using the code you provided, but I suspect it is due to Angular not knowing what location is. You can use window.location to get rid of the error, or there is also something like $location accessible in angular. You can check its implementation too.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search