angular2中router-outlet使用

前文分析了vue.js的router-view的使用,本文分析一下angular2中的router-outlet的使用。其实angular2中的router-outlet标签与vue.js中的router-view标签的作用并无二致(react中有同名标签),所以由此可见这三大前端框架有很高的相似度。

router-outlet

index.html是整个app的内容入口,如下:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>HelloWorld</title>
        <base href="/">

         <meta name="viewport" content="width=device-width, initial-scale=1">
         <link rel="icon" type="image/x-icon" href="favicon.ico">
     </head>
     <body>
        <app-root></app-root>
     </body>
</html>

app.module.ts路由配置区域,配置如下

  imports: [
     BrowserModule,
     RouterModule.forRoot(
       [
         {
    
    
          path: '',
          redirectTo:'/home',
          pathMatch: 'full'
         },

         {
    
     path: 'home', 
          component: HomeComponent 
         },
         {
    
    
          path: 'about',
          component: AboutComponent
         },
         {
    
    
          path: 'dashboard',
          component: DashboardComponent
         }
       ]
     )
 ],

配置路由的作用,即是根据不同的路由名跳转至不同的页面。
路由跳转关键代码如下:

    <app-root></app-root>

这里 相当于是局部页面的占位符。 这个区域是动态加载的,运行时,会被 app.component.html 替换掉。具体来说,就是被以下页面替换掉。

app.component.html 文件代码如下:

<div style="text-align:center">
    <h1>
     {
    
    {
    
    title}}!!
    </h1>
    <nav>
      <a routerLink="home" routerLinkActive="active">Home</a>
      <a routerLink="about">About</a>
      <a routerLink="dashboard">Dashboard</a>
    </nav>
    <router-outlet></router-outlet>
  </div>

此处的关键代码是:

    <router-outlet></router-outlet>
单页面使用两个router-outlet

父组件html:

<div style="font-size:20px;">
    <router-outlet name="left"></router-outlet> 
</div>
<div style="color:red;">
    <router-outlet name="right"></router-outlet>
</div>
<--这里name对应的left和right必须和module里面的outlet相对应-->

父组件module:

    export const rou:Routes = [
    {
    
    
        path:'',
        component:LeftComponent,
        outlet:'left'
    },
    {
    
    
        path:'',
        component:RightComponent,
        outlet:'right'
    }
]

子组件left:

<div>left</div>

子组件right:

<div>right</div>

router-outlet起到占位符的作用,可以这样理解:页面的占位符,动态加载,被替换。

猜你喜欢

转载自blog.csdn.net/weixin_41993525/article/details/110900258