Reputation: 245
I have 3 components: A, B, and C. I want to display a button named "Component B" inside component A. On clicking the button, it should display B component with a link saying "Component C". On clicking the link it should display c component which says "C component works"
The app module is:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AComponent } from './a/a.component';
import { BComponent } from './b/b.component';
import { CComponent } from './c/c.component';
@NgModule({
declarations: [
AppComponent,
AComponent,
BComponent,
CComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
The app routing module is:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AComponent } from './a/a.component';
import { BComponent } from './b/b.component';
import { CComponent } from './c/c.component';
import { AppComponent } from './app.component';
const routes: Routes = [
{
path: 'a',
component: AComponent,
},
{
path: 'a',
component: BComponent,
},
{
path: 'c', component: CComponent
},
{
path: '**', component: AppComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule { }
The app.component.html is :
<h3>Routing and Navigation</h3>
<router-outlet></router-outlet>
The A component is:
<h4>It is Component A</h4>
<a class="button" routerLink="a" routerLinkActive='active'>B component</a>
<router-outlet></router-outlet>
The B component is:
<a routerLink="b">C component</a>
<router-outlet></router-outlet>
The C component is:
<p>C component works</p>
Kindly help me with this as I am learning to route in Angular. I will be glad if I know the area of improvement in the code and a proper guidance. Thank you.
Upvotes: 1
Views: 1481
Reputation: 1870
You don't need routing at all to do what you are asking. If Component B & C are "inside" component A, then you don't route to them. you just display them.
<h4>It is Component A</h4>
<a class="button" (click)="showBFlg = true">B component</a>
<div *ngIf="showBFlg">
<app-b></app-b>
<a class="button" (click)="showCFlg = true">C component</a>
</div>
<app-c *ngIf="showCFlg"></app-c>
Upvotes: 0
Reputation: 399
here is a stackBlitz with a working example that has all 3 components.
https://angular-7ucy2h.stackblitz.io/a
the thing about angular routing is that if you want a child route to show inside of a parent route you will have to add that route as a child.
in your case C is a child of B and B is a child of A.
const routes: Routes = [
{
path: 'a',
component: AComponent,
children: [
{path: 'b', component: BComponent, children: [
{path: 'c', component: CComponent}
]},
]
},
];
Upvotes: 1