如何在Angular 8中启用组件页面之间的路由和导航

如何在Angular 8中启用组件页面之间的路由和导航

任务是通过使他们的路线在angular组件之间实现路由,当用户点击链接时,它将被导航到与所需组件对应的页面链接。

让我们知道Angular中的路由是什么

Angular 8的路由。

Angular 8 Router帮助在由用户行为触发的页面之间进行导航。当用户点击链接或从浏览器地址栏输入URL时,就会发生导航。链接可以包含对路由器的引用,用户将被引导到该路由器。我们还可以通过angular routing将其他参数与链接一起传递。

步骤:

  • 创建一个Angular应用程序。

语法:

ng new app_name
  • 对于路由,你将需要组件,这里我们做了两个组件(home和dash)来显示主页和仪表板。

语法:

ng g c component_name    
  • 在app.module.ts中,从@angular/router中导入RouterModule。

语法:

import { RouterModule } from '@angular/router';
  • 然后在app.module.ts的导入中定义路径。
   imports: [
        BrowserModule,
        AppRoutingModule,
        RouterModule.forRoot([
          { path: 'home', component: HomeComponent },
          { path: 'dash', component:DashComponent } 
        ])
      ],
  • 现在在HTML部分,为app.component.html定义HTML。在链接中,将routerLink的路径定义为组件名称。
<a routerLink="/home">Home </a><br>
<a routerLink="/dash">dashboard</a>
  • 在app.component.html中为你的应用程序应用router-outlet。 被路由的视图会在< router-outlet >
<router-outlet></router-outlet>
  • 现在只要为home.component.html和dash.component.html文件定义HTML
  • 你的angular web-app已经准备好了。

代码实现:

  • app.module.ts:
    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { RouterModule } from '@angular/router';
    import { AppRoutingModule } from './app-routing.module';
    import { AppComponent } from './app.component';
    import { HomeComponent } from './home/home.component';
    import { DashComponent } from './dash/dash.component';
      
    @NgModule({
      declarations: [
        AppComponent,
        HomeComponent,
        DashComponent
      ],
      imports: [
        BrowserModule,
        AppRoutingModule,
        RouterModule.forRoot([
          { path: 'home', component: HomeComponent },
          { path: 'dash', component:DashComponent } 
        ])
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
  • app.component.html
    <a routerLink="/home">Home </a><br>
    <a routerLink="/dash">dashboard</a>
    <router-outlet></router-outlet>
  • home.component.html
    <h1>GeeksforGeeks</h1>
  • dash.component.html
    <h1>Hey GEEKS! Welcome to Dashboard</h1>

输出:

运行开发服务器并点击链接。

如何在Angular 8中启用组件页面之间的路由和导航?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程