Skip to content

jdegand/bug-cd

Repository files navigation

Bug Cd

Angular Challenges #32 Bug Change Detection Solution

Built With

Directions

In this small application, we have a navigation menu to route our application to either barComponent or FooComponent. However our application is not loading and no errors are displayed inside the console.

Statement

The goal of the challenge is to debug this application and make it work.

Hints

Hint 1

If you comment out routerLinkActive="isSelected" inside NavigationComponent: the application loads correctly.

Hint 2

If you open the RouterLinkActive source code and go to line 196, Angular is calling this.cdr.markForCheck inside a microTask which triggers a new CD cycle. If you comment out this line, the application loads again, however the bug is not inside the Angular Framework.

Thoughts

  • App is slow and you can't refresh it.
  • I didn't like the order of the routes so I changed them. Although it doesn't really matter in this case, I always prefer to have empty routes at the bottom (with a wildcard route as the final route).
  • Having getMenu function calls inside the template is a problem.
  • Use a pipe ? ngOnChanges ?
  • I initially leaned towards ngOnChanges as many challenges I have already used pipes.
  • The fake backend response (string) actually makes this harder to fix with ngOnChanges.
  • There will be typing issues if you just pass a string to menus. Once you fix that, then you call the getMenu function inside of ngOnChanges. Then you have to worry about return types and issues in the template.
  • I think it would be preferrable to have the @Input just be the object itself. But that wouldn't be enough as you would need to pass the Input value to a function that adds the prop value inside the ngOnChanges function.
  • Ultimately, I think ngOnChanges would require too much modification to the existing code to be a realistic solution.
  • I found some great articles and there is an easy fix. Use a memo function and you can keep the function calls in the template. See this article for the memo function and explanation.

Useful Resources

  • Angular Docs - RouterLinkActive
  • Stack Overflow - how to detect a route change in angular
  • Stack Overflow - angular 8 observable not triggering change detection
  • Stack Overflow - whats the difference between markForCheck and detectChanges ?
  • Medium - difference between markForCheck and detectChanges
  • Medium - why you should never use function calls in angular template expressions
  • Blog - its ok to use function calls in angular templates
  • Dev.to - ngOnChanges best practice always use simpleChanges

About

Angular Challenges #32 Bug Change Detection

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published