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.
- ngOnChanges - Changes to input values () (before ngOnOnit)
- ngOnInit - after the data bindings have been established
- ngDoCheck - own change detection
- ngAfterContentInit - after projecting the content
- ngAfterContentChecked - Control of changes to the content
- ngAfterViewInit - after initializing the views
- ngAfterViewChecked - Control of changes in the views
- 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.
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!
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.
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.
However, if you simply want to execute a function once after initializing the inputs, the ngOnInit hook is ideal.
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.
You already have an example of this in the section Access to the lifecycle seen.
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.
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 AngularJS code:
In Angular, this principle is now perhaps a little more appropriate Projection. But this has the same function.
Instead of ngTransclude you have the directive with the appropriate name ngContent to disposal. An example of this then looks like this.
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.
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.
- Inform other components about the deletion, if necessary (optional)
- Unsubscribe connection to observables
- Disconnect from superfluous DOM events
- Stop intervals and timeouts
- Unsubscribe from global services
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.
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!
- Which framework is good for web developers
- How will the United States be remembered
- What does the military term FFI mean
- What do pilots say about Embraer planes
- How can I improve my answers 6
- Ashkenazi is an Ashkenazi Jewish family name
- What kind of flower is the 7th
- Most biostatisticians need programming
- Are these characters from a soap opera
- Why are wickets counted in Twenty20 Cricket
- When were clothing brands first made?
- Which is the most volatile halogen acid
- How to block ads in Chrome
- How do you upgrade your normal speakers?
- Why do British teenagers get so drunk
- Like to be productive
- Why do people say remember to breathe
- What is the Albanian word for drone
- Ginseng causes constipation
- What are the cons of Google Search
- How do I make 300,000 a year
- Why is DJ Khalid so popular
- Aging is good or bad
- Is Amazon Echo dot safe for children
- What is the best free MagicDraw alternative
- Why did China not take a country away from Russia
- Have you had a favorite pet
- Is the consciousness spatial or non-spatial
- How is toluene made
- How can I die at the age of 14
- Is Ayodhya in Sri Lanka
- What is a post-fault voltage
- Are potatoes banned on keto plans?