I am using Angular2. I would like to implement group panel collapsable. Toward it, there are a lot of examples using JQuery. However, I would like to implement it using original javascript. To use JQuery, I have to import the JQuery library too which might cause some additional loading. I think there may be some DOM manipulation in my future development also besides group panel. I would like to know which is better using javascript or JQuery. I know there is some trade-off between them. In the respect of performance, which way would be recommended. Using Angular2 and JQuery together is recommended approach? Please give me some advice.
-
3Possible duplicate of [How to use jQuery with Angular2?](http://stackoverflow.com/questions/30623825/how-to-use-jquery-with-angular2) – muetzerich Jan 24 '17 at 17:06
-
It's a terrible approach. Don't do it. – Daniel Beck Jan 24 '17 at 17:31
-
No this is not question about how to use Angular2 + JQuery together. This is question about is it a common and good approach generally? – Anna Lee Jan 24 '17 at 17:32
-
Could I ask why you think that? – Anna Lee Jan 24 '17 at 17:54
-
@AnnaLee Posted as an answer (sorry about the delay, SO went offline for a bit while I was typing it up) – Daniel Beck Jan 24 '17 at 18:50
1 Answers
Angular expects to be in control of the DOM, and its philosophy of how the page and the data interact mixes poorly with jQuery (in jQuery you tend to make a lot of direct DOM modifications, while in Angular the DOM is almost a side-effect representation of the scope data; modifications to the DOM made outside Angular's expected path can get blown away on the next digest, or can overwrite or destroy bindings that Angular depends on.)
Manipulating the DOM separately through jQuery is possible, so long as you use great care not to interfere with the Angular lifecycle -- but it's highly error prone unless you have a very strong understanding of Angular's DOM lifecycle and of what is and isn't safe to change. It's rarely necessary; it's almost always better to use Angular's own tools.
(Also note that Angular includes jqLite; much of the time the jQuery function you're looking for is already available without needing to install the full library.)
(If you must use jQuery, keep it within specific Components' afterViewInit
function and never try to e.g. modify the results of one component from within another.)

- 20,653
- 5
- 38
- 53
-
-
good explanation @Daniel ... I add jQuery to Angular application bundle because one 3rd party library (mergely) depends on it (I do not use jQuery in any other way in my application). Will it affect DOM rendering performance on other pages where mergely is not used? – michal.jakubeczy Apr 23 '20 at 08:27