angular9教程之路由

Fork Me On Github

主要写在模块的 -routing.module.ts 文件里

ts
  
const routes: Routes = [
];
12

routes 就是放路由的。

基本写法

显示页面,例如: home 路径显示 HomeComponent 的内容

ts
      
const routes: Routes = [
    {
        path: 'home',
        component: HomeComponent,
    },
];
123456

未匹配到指定 未找到 页面

ts
      
const routes: Routes = [
    {
        path: '**',
        component: NotFoundComponent,
    },
];
123456

指定路由重定向到新的路由

ts
       
const routes: Routes = [
    {
        path: '',
        redirectTo: 'home',
        pathMatch: 'full'
    },
];
1234567

指定路由到指定模块

ts
       
const routes: Routes = [
    {
        path: 'blog',
        loadChildren: () => import('./blog/blog.module').then(m => m.BlogModule)
    },
];
1234567

在模块中可以指定路由是否要加载模块公共模板

ts
                
const routes: Routes = [
    {
        path: '',
        component: FrontendComponent,
        children: [
            {
                path: 'home',
                component: HomeComponent,
            },
        ]
    },
    {
        path: 'blog',
        component: HomeComponent,
    },
]
12345678910111213141516

注意 frontend.component.html 必须有 <router-outlet></router-outlet> 才能加载子路由

这样 /home 就会先加载 FrontendComponent 再加载 HomeComponent 并把 HomeComponent 的内容 放在 frontend.component.html<router-outlet></router-outlet> 位置

/blog 就只会加载 HomeComponent,这样就可以实现模块内不同页面有不同的框架结构。

也可以实现 不同的页面分别由不同的公共模板

ts
                      
const routes: Routes = [
    {
        path: '',
        component: FrontendComponent,
        children: [
            {
                path: 'home',
                component: HomeComponent,
            },
        ]
    },
    {
        path: 'blog',
        component: BlogComponent,
        children: [
            {
                path: '',
                component: HomeComponent,
            },
        ]
    },
]
12345678910111213141516171819202122
点击查看全文
标签: angular
0 357 0
在 angular 项目中实现对页面的访问控制
按下回车键,焦点移动到下一个表单或提交表单
使用ng-template 显示tree结构数据
使用 ViewContainerRef.createComponent 替代 ComponentFactoryResolver
angular 12使用 KaTex 显示 AsciiMath 格式的公式