Rebuilding a component in Angular 2.1 during routing operations

Angular version 2.1.0 and router version 3.1.0 were used.

During the creation of a dashboard component, I observed that every time I route to it, it is recreated from scratch. This same behavior was noted in the Tour of Heroes demo plunker as well.

Modifications made to the DashboardComponent:

export class DashboardComponent implements OnInit {
  heroes: Hero[] = [];

  constructor(private heroService: HeroService) {
    console.log('DashboardComponent constructor')
  }

  ngOnInit(): void {
    this.heroService.getHeroes()
      .then(heroes => this.heroes = heroes.slice(1, 5));
    console.log('DashboardComponent ngOnInit')
  }
}

A link to the plunker is provided. Opening the developer console and running the plunker will generate 2 logs: DashboardComponent constructor and DashboardComponent ngOnInit. Clicking on Heroes and then back on Dashboard triggers the construction and initialization methods once again.

The plunker may be using outdated libraries. By cloning TOH from John Papa's GitHub repository (which uses the same versions of Angular and router), and adding console logs to the DashboardComponent, the same behavior was observed.

An additional method ngOnDestroy was added to the DashboardComponent, which gets called when leaving the dashboard. It appears to be a design behavior. The question arises about the benefits of this behavior and how already created components can be reused.

Answer №1

Version >= 2.3.0-rc.0

To manage when components are destroyed, recreated, or reused during routing, a customized RouteReuseStrategy can be implemented.

original

The behavior where the component is destroyed and recreated upon navigating away and back to a route is intentional and expected.

If only route parameters change but the route remains the same, the component will be retained.

Although there have been talks about implementing a custom caching strategy, as of now, no progress has been made in that direction.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Talking about "this" within the event function and how to remove the TypeScript event reference

Currently, I am working on developing a TypeScript game and facing some challenges with adding and removing a "keydown" event. The event function is currently referencing the document when I actually need it to refer to the object instance. Is there a way ...

Transfer my testing utilities from React Router version 5 to version 6

I am currently transitioning my project to React V6 router and encountering an issue with my test utility function. Every time I run the test, all my expectations fail because jest cannot locate the object. Has anyone faced this error during a similar migr ...

Unleashing the potential of an endless animation by incorporating pauses between each iteration

I am trying to create an infinite animation using animate css but I want to add a delay between each iteration. After exploring various options, I first attempted to achieve this using plain JavaScript. Here is the HTML snippet: <div id="item" class= ...

Challenges managing errors in Angular unit tests

As I continue to learn Angular, my search for information has yielded minimal results. However, one resource that stood out was a post on Stack Overflow titled How to write a test which expects an Error to be thrown in Jasmine? After reviewing the aforeme ...

The Docker environment is experiencing a sudden disappearance of Angular frontend root files

Can someone offer a hint as to why this setup is no longer functioning properly? My frontend docker file is suddenly throwing this error. It worked fine for a while in this configuration, and what's even stranger is that two previous projects operated ...

Tips for adding a new property to an array object in TypeScript using a condition

Here is an array object that I have: arr = [ { Name: "ABC", Age: 20}, { Name: "XXX", Age: 15} ]; In Typescript, I am looking to dynamically add a new property called "Flag" with a value of 1 only if the Age is greater than 15. Can someone suggest ...

Enhancing JavaScript with TypeScript: implementing functional mixins

I'm in the process of creating functional mixins using TypeScript. Below is the code I have written so far: const flying = (o: object) => { let isFlying = false; return Object.assign({}, o, { fly() { isFlying = true; return thi ...

The number in Typescript should fall between 0 and 1, inclusive

Is there a method in Typescript that guarantees the value of a number will be less than or greater than a certain threshold? Currently, it permits the specification of a range of values, but I'm unsure about comparison. This is similar to what I have ...

How can the value be accessed when using getElementById in Angular for <mat-select> elements that do not have a value attribute?

Within a loop, I have an element that has a dynamically generated id: <mat-select multiple class="dw-input" [value]="element.txn_type_id ? element.txn_type_id.split(',') : []" id="field-{{element.Name}}-txn_type_id&quo ...

What is the best way to include 'SCSS' in the 'rollup' project that I have developed?

I am embarking on the creation of a React UI library and have chosen 'rollup' as my build tool. To enhance the project, I plan to incorporate TypeScript and utilize SCSS for styling. How can I implement SCSS within this setup? You can find the s ...

Challenges faced during a tutorial on angular-meteor.com

I have recently started learning Angular 2 and Meteor, following a tutorial from However, in the third lesson, I encountered two errors in the console: refreshingclient/app.ts (18, 11): Generic type 'Array<T>' requires 1 type argument(s) ...

"Unresolved Class / Interface Error: The variable 's' is not defined

Exploring Typescript and Angular2 for the first time has been a learning experience, especially when it comes to classes and interfaces. Take a look at my interface: export interface Discount { codSco: string; desSco: string; } Now I'm atte ...

Defining our own properties within a TypeScript reference interface

Is it possible to use the type of a property of an Interface as a generic in TypeScript? I have some code that demonstrates what I'm trying to achieve: In the example below, I show how we can normally define types using enums and interfaces: enum Se ...

Ensure that Template.fromStack() includes resources with the specified logical identifiers

Currently, I am overhauling a CDK stack in TypeScript that has reached the resource limit. Given that it includes stateful resources, I need to ensure that the revamped stack points to the same resources and not new ones that could lead to unfavorable resu ...

The Angular Syncfusion schedule is unable to call upon an object that may potentially be 'undefined'

Currently, I am developing an application using Angular Syncfusion to allow users to view and book appointments. I found a helpful resource at the following link: Below you can find the code snippet I have been working on: <ejs-schedule #scheduleObj ...

Default functionality of Typescript paths imports fails to operate properly

Can anyone help me figure out how to set up default imports in my .ts files using the paths specified in my tsconfig.base.json? I have this file defined as default in the File Type > Typescript Config. https://i.sstatic.net/LvBGV.png The import statem ...

Encountering issues with running npm install on a local Angular project

Whenever I try to execute npm install on my local Angular project, I encounter the following errors: C:\Projects\Angular>npm install npm ERR! code ENOENT npm ERR! syscall spawn git npm ERR! path git npm ERR! errno ENOENT npm ERR! enoent Error ...

Adjust the range slider's color depending on its value

I'm looking to customize the color of a range slider as its value increases, switching from red to green. Below is the code I've tried, but it's not quite working as intended. The goal is for the color to change based on the value of masterR ...

Angular 2 dropdown list that allows users to add a personalized value in the HTML code

Here is the scenario I am dealing with We are displaying a fixed dropdown list to the user For example, a dropdown list has 4 options such as apple, orange, grape, pineapple and 'create your own' If the user is not satisfied with the provided ...

Passing events between sibling components in Angular 2Incorporating event emission in

Having some trouble emitting an event from one component to another sibling component. I've attempted using @Output, but it seems to only emit the event to the parent component. Any suggestions? ...