POV
POV

Reputation: 12025

Why does not work child route for component?

File AppRoutingModule contains:

const routes: Routes = [
{
    path: "events",
    component: EventComponent,
    children: [
      {
        path: 'add',
        component: AddEventComponent
      }
    ]
  },
];

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

I try to reach AddEventComponent by url: localhost:4200/events/add

It is not opened, without errors.

Component AddEventComponent was registered in add-event.module.ts:

import { NgModule } from "@angular/core";
import { SharedModule } from 'src/app/SharedModule';
import { CompanyService } from 'src/app/api/CompanyService';
import { AddEventComponent } from './add-event-component';

@NgModule({
  imports: [SharedModule],
  declarations: [AddEventComponent],
  exports: [AddEventComponent],
  providers: [CompanyService]
})
export class AddEventModule { }

Then AddEventModule was added to main AppModule:

@NgModule({
  declarations: [
  ],
  imports: [
     AddEventModule
]});

So,I need to open component AddEventComponent by url: localhost:4200/events/add, now it always opens parent EventComponent

AppModule:

@NgModule({
  declarations: [
    AppComponent,
    NofoundComponent
  ],
  imports: [
    CommonModule,
    BrowserModule,
    HttpClientModule,
    SharedModule,
    LoginModule,
    LanguageModule,
    EventModule,
    AddEventModule,
    VisitorModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: CustomTranslateLoader,
        deps: [HttpClient]
      }
    }),

    SocketIoModule.forRoot(config),
    AppRoutingModule
  ],
  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: RequestInterception,
    multi: true,
  },
    EventsService, VisitorsService, UserService, ExportService, AuthenticationGuard],
  exports: [TranslateModule, AddEventModule],
  bootstrap: [AppComponent]
})
export class AppModule { }

Upvotes: 0

Views: 44

Answers (1)

Alexander Staroselsky
Alexander Staroselsky

Reputation: 38847

To your component EventComponent add a <router-outlet></router-outlet> as you are using child routing. This is needed to render routes/components defined in the children route configuration property.

EventComponent:

<!-- existing component content -->
<router-outlet></router-outlet>

With this, any components specified in children would render within EventComponent in place of the <router-outlet></router-outlet>.

If you weren't using the children property in the route configuration, then you would not need an additional <router-outlet></router-outlet> in EventComponent:

const routes: Routes = [
  { path: "events", component: EventComponent },
  { path: "events/add", component: AddEventComponent }
];

With that however, AddEventComponent would not render within EventComponent, but instead of EventComponent.

Hopefully that helps!

Upvotes: 1

Related Questions