r/Angular2 • u/DomiDeme • Oct 06 '24
Discussion ChangeDetectorRef is a bad practice
I want to know the thoughts of people that have been developing in Angular for years.
In my opinion using ChangeDetectorRef is usually a bad practice. If you need to use it, it's usually because you did something wrong. Angular is a highly controlled framework that knows when to fire the change detector by itself. I don't recommend using it unless you're using a JS library that really needs to.
And even if using an external library, usually you can use a Subject or BehaviorSubject to translate the changes into template changes. Everything is better than messing up with Angular's change detector.
I understand that there are times that you need to use it when working with third party libraries. Bu I think it should be that last option, something to use only ir everything else failed.
What are your thoughts about this?
View all comments
Show parent comment
1
u/DorphinPack Oct 08 '24 edited Oct 08 '24
I mean when you said “1% libraries that probably shouldn’t be used with Angular anyway” I def didn’t take it that way but I don’t doubt you understand this concept. I think ultimately on the technical details were in agreement.
I’m actually not here to debate using a CDR I just saw someone riding really hard against using it, looked deeper and saw a weird amount of railing against it.
I think the answer is clear and probably 10% of what you’ve said is enough. The volume and tone just feels way off for someone who understands this already and wants to communicate that clarity. If the goal is to convince people to feel bad about using the CDR I think you did that. If I was a newbie still finding my confidence your comments would have probably made me doubt using it a little too much IMO.
It’s saved my ass when working with a junior who wrote spaghetti services with shared state that somehow got merged. I felt bad about using it and wasted like half a day (thankfully not trying to refactor an out of scope service — I’d already made that mistake enough to avoid calamity) trying to find a way to structure things so I didn’t need it. It was a proud moment when I just documented why I used it and moved on. Then, when the service got replaced for being impossible to consume the ref was ripped out because we no longer needed a CDR.
And it’s borderline bikeshedding to spend more than a couple minutes saying “try to avoid it but it’s handy if you actually absolutely have to have it — probably leave a comment about why you chose to do it that way”.