Lifecycle Hooks

Learn how lifecycle hooks can help us move the modal when the component is initialized.

In the previous lesson, we saw how the modal could cause complications because it’s CSS properties can be affected by the parent component. The best way to combat this issue is to move the component to be a direct child of the <body> element. We’ll want to do so with code.

It is possible to just manually move the component. However, we want to be able to drop the modal in any application. It would be a hassle to continually remember to load the component in the root most location in our application. It’s much more convenient if it’s able to move itself.

About lifecycle hooks

Before we move the element, we need to know when to move it. We want to move the element when the component is initialized for two reasons. First, it’s the earliest time we can move it. Second, we’ll have access to the element at this point.

Angular provides lifecycle hooks, which are functions that we can define in our component. If they’re defined, Angular will call them during the lifetime of the component. If you’re interested in a complete list of lifecycle hooks, you can find them here.

We’ll briefly go over the most common ones you’ll use.

  • ngOnInit(): This gets called when the component is initialized. We’ll have access to the component’s properties and methods. This includes the element.
  • ngOnDestroy(): This gets called before Angular destroys (removes) a component. (e.g.: when we navigate to a different route).
  • ngOnChanges(): This gets called whenever any of the properties of the component is updated. This includes data passed down from the parent component.

Loading the modal

As you can already tell, we’ll want to use the ngOnInit() hook to move the component. By default, Angular will define the function for you when you generate a new component. Let’s look inside the modal.component.ts file.

Get hands-on with 1200+ tech skills courses.