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
Well i couldn't fix location is not defined error but instead of that i used router service, code below
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.