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
}
}
5
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 === '/';
}
}