在Angular 2中,可以使用Angular的路由模块来实现路由到新页面的功能。下面是一个包含代码示例的解决方法:
首先,在Angular项目的根模块中导入所需的模块和组件:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { HomeComponent } from './home.component';
import { NewPageComponent } from './new-page.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'new-page', component: NewPageComponent }
];
@NgModule({
imports: [BrowserModule, RouterModule.forRoot(routes)],
declarations: [AppComponent, HomeComponent, NewPageComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
接下来,创建两个组件:HomeComponent和NewPageComponent。这些组件将分别在主页和新页面上显示。
import { Component } from '@angular/core';
@Component({
selector: 'app-home',
template: 'Welcome to the Home Page
'
})
export class HomeComponent { }
@Component({
selector: 'app-new-page',
template: 'Welcome to the New Page
'
})
export class NewPageComponent { }
然后,在根组件的模板中添加路由链接:
My Angular App
最后,编译并运行应用程序。当点击“New Page”链接时,将导航到新页面,显示“Welcome to the New Page”的标题。
希望这个解决方法能帮助到你!
上一篇:Angular 2 - 链接来自 API 数据以在新窗口中打开
下一篇:Angular 2 - Promise chaining - promise not getting called(Angular 2 - Promise链式调用 - promise未被调用)