How to Lazy Load Components in Angular 4 in Three Steps
// angular按模块开发,跟模块,特性模块,核心模块(整个应用只在跟模块只加载一次),惰性加载模块等 只是有一个问题,即在惰性加载模块里(selector方式的模板方式,即
<app-title [subtitle]="subtitle"></app-title>
),调用特性模块或者核心模块的component对应的selector时,总是提示错误,即核心模块或者特性模块的component共享到惰性加载的模块时,有问题
'app-title' is not a known element: 1. If 'app-title' is an Angular component,then verify that it is part of this module. 2. If 'app-title' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. (" [ERROR ->]<app-title ></app-title> 网上有人遇到同样的问题,https://github.com/angular/angular/issues/12809,貌似没有解决 https://angular.cn/guide/ngmodule
// 另一个模块惰性加载的例子 https://angularfirebase.com/lessons/how-to-lazy-load-components-in-angular-4-in-three-steps/ Step 1 - Create a new App with Routing 初始化一个带routing的新project ng new lazyDemo --routing
Now add a link to the lazy url in the app component.
Step 2 - Generate the “Lazy” Module Let’s create a module that will be lazy loaded,along with a couple components. The --flat flag prevents a directory from being created,then we can easily add components to the module via the Angular CLI. Step 3 - Point the App Router to the Lazy Module Lazy loading is a technique in Angular that allows you to load JavaScript components asynchronously when a specific route is activated. This can add some initial performance during the initial load,especially if you have many components with complex routing. There are some goodpostsabout lazy loading in angular,but I wanted to simplify it further. This lesson will show you how to enable lazy loading in 3 easy steps with a brand new app.
Step 1 - Create a new App with Routing Our app will load the
Now add a link to the lazy url in the app component.
Step 2 - Generate the “Lazy” Module Let’s create a module that will be lazy loaded,along with a couple components. The
Inside the lazy module we need to import the
And here’s what the
Step 3 - Point the App Router to the Lazy Module The final step is to point the lazy route to the lazy module from the app router. We can do this with the
Verify Lazy Loading is Working Let’s make sure Lazy Loading is working. In chrome,open developer tools and click the network tab. When you navigate to the lazy url,you should see a The lazy loaded module is the last chunk.js file in the chrome network logs When you take a look inside this file,you should see a bunch ofwebpackJavaScript code with related to the lazy module and its components. Looking inside,we see that is a bunch of JavaScript webpack code That’s it for lazy loading components in Angular. Good luck! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |