Laura Seidel
Laura Seidel

Reputation: 61

Links with href not working in Angular Application

I just deployed an angular app into Azure as a Static Web App.

When I try to navigate between views I get a 404 error when navigating by link but navigating via angular/router works fine. Locally both methods work, the problem only occures once deployed into Azure. I have tried solving the issue like described here, but that did not work for me.

For example:

app.component.ts

import { Router } from '@angular/router';
...

goToNews(): void {
    this.router.navigate(['/news'])
}

app.component.html

<a class="nav-link" (click)="goToNews()">News</a> <!-- works -->
<a class="nav-link" href="/news">News</a>         <!-- does not work -->

The first link works fine but the second link does not. Typing the route to the view in the url also results in a 404 error.

Does anybody know, why that happens or how to solve it?

Thank you :)

Upvotes: 0

Views: 9065

Answers (1)

H3AR7B3A7
H3AR7B3A7

Reputation: 5261

Angular Router

The issue there is that the href of the anker element is unaware of your Angular Router. The right way to use angular router is to use the routerLink directive:

<a routerLink="/news">News</a>

You can also use relative path or a full path using href:

<a href="https://angular-ivy-7dotr6.stackblitz.io/other">Other</a> | <!-- BAD PRACTICE-->
<a href="../home">Home2</a> <!-- BAD PRACTICE-->

However by doing this you are not using the angular router and the browser will seem like it is refreshing. This is a bad practice, but I included it in an example on Stackblitz for you to see the difference and understand what is going on.

Upvotes: 3

Related Questions