Angular routes

Asked

Viewed 1,182 times

1

I’m studying routes at the angle and following a tutorial from their website. They ask to create an app-routing.module with the ng generate module app-routing --flat --module=app in cmd, my code stops working when I tag the app.component.html

app-routing.module:

import { NgModule }             from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { HeroesComponent }      from './heroes/heroes.component';

const routes: Routes = [
  { path: 'heroes', component: HeroesComponent }
];

@NgModule({
  exports: [ RouterModule ],
  imports: [ RouterModule.forRoot(routes) ],
})
export class AppRoutingModule {}

app.component.html:

<h1>{{title}}</h1>
<router-outlet></router-outlet>
<app-messages></app-messages>

And I managed to make it work, but for that I had to change the app-routing.module and stayed like this:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import{ HeroesComponent } from './heroes/heroes.component';

const routes: Routes = [
{ path: 'heroes', component: HeroesComponent}
];

export const routing = RouterModule.forRoot(routes)

and I had to change the app.modulets.:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HeroesComponent } from './heroes/heroes.component';
import { HeroDetailComponent } from './hero-detail/hero-detail.component';
import { MessagesComponent } from './messages/messages.component';
import { routing } from './app-routing.module';//<-coloquei isso

@NgModule({
  declarations: [
    AppComponent,
    HeroesComponent,
    HeroDetailComponent,
    MessagesComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    routing//<-coloquei isso
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

I found several tutorials with the solution that does not work and found a few with the solution that worked, so my question is:

  • because the second solution works and the first not?
  • because there are so many places showing the wrong solution?
  • there is a better way to create these routes?

1 answer

1

If you prefer, you can do it directly in ng module.:

const appRoutes: Routes = [
  { path: 'registrar', component: RegistrarComponent },
];

Imports:

imports: [
    RouterModule.forRoot(
        appRoutes,
        { useHash: true, enableTracing: true }
    ),
],

And on app.component.html:

<div class="wrapper">
   <div class="content-wrapper">
       <router-outlet></router-outlet>
   </div>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.