React hooks to make classes obsolete

The Angular Component Lifecycle

At the end of our Angular beginners tutorial, we only briefly introduced you to the topic of component lifecycle, so that you can at least start with the term or have heard of it before. In this article we want to take a closer look at the life cycle and the associated hook functions.

The life cycle of a component

When running an Angular application, each component goes through different stages. First, Angular creates the component. Then, of course, the associated template must also be rendered so that the user can see it. The data bindings are established so that you can react to user interactions with your app and programmatic changes are automatically visible to the user.

Last but not least, it can of course also happen that a component is removed again. This can happen, for example, by using structural directives such as or, or by exchanging the content when changing the route.

In Angular, one component can use other components, which creates a dependency between them. For this reason, Angular takes care of these as well. The process described above naturally also applies to all child components. Various states can occur here again. A child component could be removed or inserted.

The appropriate name basically says everything about the function: The component lifecycle maps the entire life of a component and gives us access to its most important states.

Access to the life cycle

As we will see in the course of the article, it is often necessary to react to certain events in the life cycle of a component. For this purpose, Angular offers us various interfaces that we can implement. Each interface expects the implementation of a function of the same name with the prefix, which is executed when the corresponding event occurs. They are also called hooks.

By default, there are the following hooks, which are also executed in the following order the first time they are used.

  1. ngOnChanges - Changes to input values ​​() (before ngOnOnit)
  2. ngOnInit - after the data bindings have been established
  3. ngDoCheck - own change detection
  4. ngAfterContentInit - after projecting the content
  5. ngAfterContentChecked - Control of changes to the content
  6. ngAfterViewInit - after initializing the views
  7. ngAfterViewChecked - Control of changes in the views
  8. ngOnDestroy - before removing the component

Assigning the interface to the component is optional, but avoids typing errors. For each hook there is a corresponding interface without the prefix ng.

interfaceHook
OnChangesngOnChanges
OnInitngOnInit
DoCheckngDoCheck
AfterContentInitngAfterContentInit
AfterContentCheckedngAfterContentChecked
AfterViewInitngAfterViewInit
AfterViewCheckedngAfterViewChecked
OnDestroyngOnDestroy

Do not worry if you are not yet familiar with many terms, such as projection. These are explained explicitly in the appropriate section.

But first of all it is interesting how the use of the hooks in the source code could look like. To do this, we tinker a small component that the ngOnInit Hook uses.

All interfaces can be easily accessed via a angular2 / core getting charged. Then you have to indicate that your component implements the corresponding interface. Now the ngOnInit-Function executed after successful initialization of the component.

The hooks in detail

In the following section we will introduce you to the meaning and possible use of the individual lifecycle hooks in detail. To do this, we will go through them sorted according to their first execution. It should be noted that when a component is created, its constructor is executed. At this point in time, the data bindings have not yet been established!

Attention: Values ​​of the inputs that have already been set are not yet available in the constructor, as the data binding has not yet been established!

ngOnChanges

After the component has been created, the data bindings are established. This means that changes to the entries may already be made. If we take the above source code, then at the beginning is already Surname set. These changes are then applied to the ngOnChanges communicated. The later process for checking changes is called Change Detection in Angular (in Angular 1 contexts as Dirty checking implemented). After each change detection, the ngOnChanges Hook executed if there are changes.

Important: The first ngOnChanges call is made before ngOnInit!

The function receives a so-called change object whose values ​​are of the SimpleChange type as a parameter. So there are separate classes in Angular to represent changes.

Let's use the code example above and modify it so that we use the ngOnChanges hook.

As you can see, the keys exist on a SimpleChange object currentValue and previousValue. It gives you access to the current - changed - and the previous value of the inputs.

Note: Every SimpleChange object also has an isFirstChange function that you can use as a value true or false returns if it is about the initial setting or normal changes.

However, if you simply want to execute a function once after initializing the inputs, the ngOnInit hook is ideal.

ngOnInit

As described in the last sentence of the previous section, after the first execution of the ngOnChanges hook, the ngOnInit hook takes effect in order to react to the initialization of the inputs.

Here is also the space for asynchronous code that should be executed after the component has been created.

Note: The constructor of a component should only be used for dependency injection. Everything else can be moved to the ngOnInit hook.

You already have an example of this in the section Access to the lifecycle seen.

ngDoCheck

During the course of the article you will occasionally read the word change detection. Simply put, this is a function that checks and detects whether the input values ​​of the component have changed.

By default, the hook is executed very frequently, as it is closely linked to this change detection cycle of the app. An Angular application reacts internally to a wide variety of circumstances and interactions in order to start this process. Usually this happens from the topmost component to the last children (Top-to-bottom). It does not matter whether the changes are made in the current component or in a completely different part of the application. As an example, a simple click can trigger an update of all components.

Important: The ngDoCheck Hook is always executed when the component is to check its input values ​​for changes. This can happen very often, depending on the active change detection strategy.

Your own change detection function should therefore be implemented with high performance in order not to block the further execution of the application.

Another small example follows. You should try it out a little until you know when and how often this hook is executed!

ngAfterContent and ngAfterView

Next we want to look at the hooks, which may not tell you much at first glance or you don't even know what they could mean.

That’s the beginning ngAfterContent Hooks. We take a short excursion away from hooks and the component lifecycle.

Content and Components

First of all, it should be clarified what could be meant by content in the context of components. For that we will now go a little further.

In the Angular context, components are nothing more than a more special form of directives. As we know, directors can have their own templates - as a template string or via an extra template file. These are compiled and the data binding is set up for the corresponding context.

In the first version of the framework (AngularJS) there is a little special feature called directives Transclusion. There can be additional content between the opening and closing directive tag. This is then, so to speak, outside of the directive itself, because it works internally with its own template.

Using the ngTransclude directive, this “outer” content can be integrated into the template of your own directive.

The template:

The AngularJS code:

In Angular, this principle is now perhaps a little more appropriate Projection. But this has the same function.

Important: The term is used in connection with components / directives Content for the content between the start and end tags of the selector.

Instead of ngTransclude you have the directive with the appropriate name ngContent to disposal. An example of this then looks like this.

The template:

The component:

In addition, ngContent can be used via the attribute select a selector can be passed to project only certain content.

How ngAfterContentInit works

Now when it's finally clear what Content means, of course, the associated hooks also make more sense.

The ngAfterContentInit hook is only executed once at the beginning if the content between the component tags was projected at the point of the ngContent. This completes the initialization of the component content, so to speak.

We will forego the code examples in the following, as they are structured in the same way as the ones presented so far.

How ngAfterContentChecked works

After the content has been initialized, it is checked once for possible changes. After that, this hook is closely linked to Angular's change detection, which means that it is also called quite frequently.

Views and Components

In contrast to component content, a view represents the actual template of the component in connection with the data bindings (ViewModel). So if you are talking about View or ViewChildren, you are talking about the actual content of the component or its child elements or child components.

How ngAfterViewInit works

This hook behaves like the ngAfterContentInit hook. Only this is carried out once here after the views have been initialized.

How ngAfterViewChecked works

Immediately after the views have been generated, they are checked for changes, as these could have changed again immediately. After that, this hook is closely linked to Angular's change detection, which means that it is called quite often.

ngOnDestroy

As sad as it sounds, at some point a component will come to an end. Be it through a cheeky route change by the user or through structural directives that simply throw the element out of the DOM. This hook function is called shortly before the component is destroyed. This means that there is enough space here to clean up properly, so that no unnecessary traces are left behind (which are not captured by the garbage collector - keyword memory leaks).

The following is a list of things you should definitely do in ngOnDestroy.

  1. Inform other components about the deletion, if necessary (optional)
  2. Unsubscribe connection to observables
  3. Disconnect from superfluous DOM events
  4. Stop intervals and timeouts
  5. Unsubscribe from global services
Important: Try to dispose of all things that the garbage collector cannot clean up yourself!

Order of execution

The following graphics give you an overview of when and in what order the lifecycle hooks are executed after a component has been created and after a change in the app that triggers a new change detection cycle.

First, let's look at the hooks that were executed when creating a component.

If change detection is triggered on a component after initialization, we have access to the following hooks within this component.

Note: After executing the ngOnChanges hook, Angular checks again for changes, whereby ngDoCheck, ngAfterContentChecked and ngAfterViewChecked are executed again. If Angular detects changes again, you will receive a warning in the browser's JavaScript console in developer mode.

Conclusion

We hope to have brought you another important part of Angular. Note that you only use the constructor of a component to include dependencies. The ngOnInit Hook exists for all other applications, e.g. loading initial data from an interface. At the end, don't forget to clean up and resolve leftovers, such as event or observable subscriptions, as these are not automatically removed from the memory by the garbage collector. But you have already found out the exact details in the article;). Furthermore, similar hooks have already found a place in the Angular 1 (version 1.5.3) components.

Have fun learning and programming with Angular!