LABS
COOKIES

Component Destruction

Git diff Code changes
Chapter Objectives
  • Understand component lifecycle

    Learn about the lifecycle hooks in Angular components.

  • Implement cleanup logic

    Master the ngOnDestroy hook for proper component cleanup.

  • Handle subscriptions

    Learn how to properly manage and clean up subscriptions.

When you submit the form, the task property of TaskFormComponent is populated with the values you entered in the form. For example, given that you filled in the name and description fields, the task property will be:

task = {
title: "My new task",
description: "Your nice description.",
};

By submitting the form and navigating to a new page, you also leave the TaskFormComponent. When you leave a component, it is destroyed.

Thus, when navigating back to this form, the task property will be empty:

task = {
title: "",
description: "",
};

A new instance of the TaskFormComponent is created each time you access it. Therefore, any local state you define in the component is lost when you navigate to another route.

Note

This is why you use the TaskService to store the new task. The service is a singleton, meaning it’s a unique instance shared across the application. Unless you force the application to reload in the browser, the tasks you’ve added will be preserved.

What you've learned

In this chapter, you learned about the Angular component lifecycle and how local state is reset when a component is destroyed and recreated. You also learned why services are used to persist data across navigation.