Search code examples
angularangular-routerrouterlink

Routes in angular 19 do not change anything in the interface


I have a simple route system in Angular 19, basically it is the home page and an about page that are between a header and a footer. However, despite the URL changing when clicking on the redirect link, nothing happens in the interface and an error is not generated. I looked for answers here in the community but all the problems I found involved treatment on the routes, which is not my case since the route is very simple

export const routes: Routes = [
    {path: '', component: FormularioComponent},
    {path: 'about', component: AboutComponent},
];

Follow the link to the project in the git repository:

https://github.com/ViniciusDevelopment/modelo19

thank you in advance


Solution

  • Make sure you have add RouterLink to the imports array of the standalone component, this is essential for angular routing, you can also include RouterModule instead.

    @Component({
      selector: 'app-header',
      imports: [
        CommonModule, 
        ButtonModule, 
        NgOptimizedImage, 
        RouterLink, // <- changed here!
    ],
      templateUrl: './header.component.html',
      styleUrl: './header.component.scss'
    })
    
    export class HeaderComponent{
      
    }
    

    When using routerLink make sure you do not have any href added, the href will refresh the entire page, which routerLink will just change the route without refresh.

    Before:

    <a routerLink="/about" href="/about" class="button block py-2 pr-4 pl-3 text-black rounded  lg:bg-transparent lg:text-primary-700 lg:p-0 " aria-current="page">About</a>
    

    After:

    <a routerLink="/about" class="button block py-2 pr-4 pl-3 text-black rounded  lg:bg-transparent lg:text-primary-700 lg:p-0 " aria-current="page">About</a>
    

    Final Header HTML:

    <header>
        <nav class="border-gray-200 px-4 lg:px-6 py-2.5 shadow-md mb-10 ">
            <div class="flex flex-wrap justify-between items-center mx-auto max-w-screen-xl">
                <a routerLink="/" class="flex items-center">
                    <img ngSrc="imagens/logo/logo.webp" alt="Logo" width="200" height="200" priority>
                </a>
               
                <div class=" justify-between items-center w-full lg:flex lg:w-auto lg:order-1 text-black" id="mobile-menu-2">
                    <ul class="flex flex-col mt-4 font-medium lg:flex-row lg:space-x-8 lg:mt-0">
                        <li>
                            <a routerLink="/about" class="button block py-2 pr-4 pl-3 text-black rounded  lg:bg-transparent lg:text-primary-700 lg:p-0 " aria-current="page">About</a>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>
    </header>