首页 > 解决方案 > 当我点击另一个页面的链接时,我希望我的主页被替换,但是,另一个页面被添加到我的主页

问题描述

我正在尝试向我的网络应用程序添加第二个页面,但是第二个页面的 HTML 被添加到我的主页。为什么?

应用程序路由.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';
}

在示例代码中:单击时“转到其他页面”链接仍在页面上,而我希望其他页面仅包含app.other-page.html.

标签: angularurl-routing

解决方案


在您的示例中,当您导航到“/otherpage”时,将显示组件 OtherPage 的内容而不是router-outlet. 这意味着周围的一切都router-outlet将始终显示出来。把标题放在前面是有意义的router-outlet

有关更多信息,您可以阅读角度路由器文档。https://angular.io/guide/router


推荐阅读