angular9教程之分模块开发

Fork Me On Github

为什么分模块

每一个模块都是分开打包的,只有用到模块才会加载模块的资源,因此可以加快第一次打开的时间,减少不必要的加载

生成

生成一个 frontend 模块,并创建路由模块

 
ng g module frontend --route frontend --module app.module
1

在 frontend 模块下继续添加模板

 
ng g module frontend/blog --route blog --module frontend.module
1

分配路由到模块

src/app/app-routing.module.ts

ts
               
const routes: Routes = [
    {
        path: 'frontend',
        loadChildren: () => import('./frontend/frontend.module').then(m => m.FrontendModule)
    },
    {
        path: '', // 默认跳转到 frontend 模块
        redirectTo: 'frontend',
        pathMatch: 'full'
    },
    {
        path: '**',  // 其他没有匹配到的路径都跳转到 frontend 模块
        redirectTo: 'frontend'
    },
];
123456789101112131415

添加公共页面

修改 src/app/frontend/frontend.component.html

html
         
<header>
    导航栏
</header>
<router-outlet></router-outlet>
<footer>
    <div class="copyright">
        <p>Copyright ©zodream.cn, All Rights Reserved.</p>
    </div>
</footer>
123456789

<router-outlet></router-outlet> 是必须的,是根据子路由加载页面的

添加首页

 
ng g component frontend/home
1

绑定路由

修改 src/app/frontend/frontend-routing.module.ts

ts
                   
const routes: Routes = [
    {
        path: '',
        component: FrontendComponent,
        children: [
            {
                path: 'home',
                component: HomeComponent,
            }, {
                path: '',
                redirectTo: 'home',
                pathMatch: 'full',
            }, {
                path: '**',
                component: HomeComponent,
            }
        ]
    },
];
12345678910111213141516171819

测试

  
ng serve --open
12

出现一下内容则表示正常了

点击查看全文
标签: angular
0 431 0
在 angular 项目中实现对页面的访问控制
按下回车键,焦点移动到下一个表单或提交表单
使用ng-template 显示tree结构数据
使用 ViewContainerRef.createComponent 替代 ComponentFactoryResolver
angular 12使用 KaTex 显示 AsciiMath 格式的公式