I am trying to add a second page to my web app, but instead, the second page's HTML is added to my homepage. Why?
app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { OtherPage } from './app.other-page';
const routes: Routes = [
{ path: 'otherpage', component: OtherPage },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
app.component.html
<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
<h1 *ngIf="'test' === str">It's true!</h1>
<a [routerLink]="['/otherpage']">Go to Other Page</a>
<router-outlet></router-outlet>
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
title = 'angular-test';
}
app.other-page.html
<h1>This is the other page</h1>
app.other-page.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.other-page.html',
})
export class OtherPage {
title = 'angular-test';
}
In the example code: the "Go to other page" link is still on the page when clicked, while I'd rather the other page consist of only app.other-page.html
.
In your example, When you navigate to "/otherpage", the content of the component OtherPage will be displayed instead of router-outlet
.
That means that everything that is around router-outlet
will be always displayed. It makes sense to put the header before router-outlet
.
For more informations, you could read the angular router documentation. https://angular.io/guide/router