Fireship · @fireship
Lazy Loading Components in Angular 4
Uploaded July 8, 2017 · Length 2:40
Summary
angular 4 lazy loading technique for improving app performance by rendering components asynchronously
- angular 4 lazy loading
- angular performance optimization
- component rendering
- route activation
Transcript preview
The first 2 minutes of the transcript. Select a timestamp to watch that moment on YouTube.
- 0:00
in this episode we're going to implement
- 0:02
lazy loading with angular 4 lazy loading
- 0:05
is a technique that allows you to render
- 0:07
components asynchronously when a certain
- 0:10
route is activated this can help with
- 0:12
the initial loading performance of an
- 0:13
angular app let's get started by
- 0:16
building a new app from scratch with the
- 0:18
angular CLI make sure to pass the
- 0:21
routing flag so angular builds a default
- 0:23
router for
- 0:24
us let's start in the app component HTML
- 0:27
and just set a router link going to the
- 0:29
lazy loaded component which in this case
- 0:31
will be activated on lazyload me the
- 0:35
next step is to build the lazy loaded
- 0:37
module as well as its
- 0:39
components when building the lazy module
- 0:42
we want to pass the flat flag to keep it
- 0:44
in the root directory then for each
- 0:47
component we can pass the module flag
- 0:49
followed by lazy that will automatically
- 0:52
assign these components to the lazy
- 0:54
module inside the module itself we're
- 0:57
going to import the root module
- 1:00
then Define an array of routes in this
- 1:03
case we just have one route that points
- 1:04
to load me that imperatively loads the
- 1:07
lazy parent component when importing the
- 1:09
router module we use the for child
- 1:12
function and we pass it the routes array
- 1:14
that we just created there's nothing
- 1:16
special about the parent component it's
- 1:18
all boilerplate code and it just Loops
- 1:20
over the child component the final step
- 1:23
is to point the app router to this new
- 1:26
module in the route definitions we
- 1:29
create a new out whose path is lazy then
- 1:32
use the load children property to point
- 1:34
to that module so we point to the file
- 1:37
path for the module and then use a hash
- 1:39
followed by the actual class of the
- 1:41
module itself the end result is the lazy
- 1:44
module is only loaded when this route is
- 1:47
activated let's make sure it's working
- 1:49
in the browser open Chrome developer
- 1:51
tools and then go to the network tab
- 1:54
when we activate the route we should see
- 1:56
that components rendered as well as a
- 1:58
chunk. Js file rendered in the network


