Angular 2: routerLink does not allow

  • Angular Version: 2.1.0
  • Router Version: 3.1.0

I am learning routing in Angular 2, and custom segments are not added to the url when the link is clicked and components are not loaded.

Manually entering segments into the address bar works, and the component is loaded into <router-outlet></router-outlet>, but instead I want it to work as expected by clicking the link inside the directive routerLink.

I have been following the documentation router and still have bad results.

Here is a very similar question , but have not yet found solutions that work for me.

Two common solutions that I came across:

  • Case-sensitive routerLink bandwidth
  • Not having <base href='/'>the topindex.html

Also there are no errors in the console window in Chrome

So, before continuing, I just wanted to give up the obvious solutions.

Here is what I did to configure my custom router:

1. Configure user routes (routes.ts)

import { Routes, RouterModule } from '@angular/router';
import { RecipesComponent } from './recipes/recipes.component';
import { ShoppingListComponent } from './shopping-list/shopping-list.component';

//TODO Fix routing bug (not switching on click or displaying in URL)
export const APP_ROUTES: Routes = [
    {path: '', redirectTo: 'recipes', pathMatch: 'full'},
    {path: 'recipes', component: RecipesComponent},
    {path: 'shopping-list', component: ShoppingListComponent}
];

/*Set routing up for root of app*/
export const routing = RouterModule.forRoot(APP_ROUTES);

2. Import routes worldwide (app.module.ts)

import { routing } from './routes';//Custom routes file

    @NgModule({                     
      // Declarations removed for bravity
      imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        routing
      ],
      providers: [ShoppingListService],
      bootstrap: [AppComponent,]
    })
    export class AppModule { }

3. Set the RouterOutlet directive (app.component.html)

<rb-header></rb-header>
<div class="container">
  <router-outlet></router-outlet>
</div>

4. Implement routerLink with static segments (header.component.html)

<ul class="nav navbar-nav">
    <li><a routerLink="/recipes">Recipes</a></li>
    <li><a routerLink="/shopping-list">Shopping List</a></li>
</ul>

The documentation router says it is used routerLinkfor static segments and is [routerLink]intended to use parameters for transmission. I tried both approaches, but they still present the same result.

+4
source share
1 answer

.

?

component.html, , "name" - Angular 2, , "recipe".

<h4 class="list-group-item-heading">{{recipe.name}}</h4>

Fix

, :

<h4 class="list-group-item-heading">{{recipe?.name}}</h4>

- , -dev-, ,

0

Source: https://habr.com/ru/post/1665187/


All Articles