Reputation: 147
We are undergoing an project in Angular 5/6 where we get prebuilt HTML pages, that use jQuery, gridstack.js and CSS for UI, that we'll implement as components. Assuming it's not possible to rewrite all the jQuery and JS code in Angular, is there any way to run the jQuery code provided in the tag directly in Angular?
I have already tried importing jQuery as:
import $ from 'jQuery';
Here is a sample of the code:
<script type="text/javascript">
$(function () {
$('.grid-stack').gridstack({
width: 12
});
$(".accordion-toggle").click(function () {
$(this).toggleClass("activu");
$(".accordion-toggle").not(this).removeClass("activu");
})
var options = {
float: true
};
$('.grid-stack').gridstack(options);
</script>
Upvotes: 0
Views: 75
Reputation: 154
You can use jQuery in your angular project. Normally jQuery based DOM manipulation is not the standard way for angular but in some cases we have to jQuery plugins for certain features.
Steps:
Import jQuery script in your index.html
<script src="assets/js/jquery.min.js"></script>
Import your plugin css/js in .angular-cli.json
inside styles and scripts arrays
Inside the component where you want to use it , declare jQuery.
declare var $ : any;
Use in directly in your component. If plugin needs to be initialised , you can do it inside ngOnInit
Upvotes: 0
Reputation: 5805
It is possible and could be a good intermediate step on a migration path.
I am working on a project right now where we have a JQuery-based app. It has a lot of CSS and HTML code inside the JS code to handle state changes and change content and styling accordingly. It is relatively messy.
We took a number of steps of migrating to Angular, with the first being what you are describing. It definitely already helped gain an overview of the code base and structure the code in a much more maintainable way than it was before.
declare const $: any;
.It proved to be a viable strategy. We were first considering re-writing the entire project, but like this we always had a running version, could continuously run UI tests against it and piece by piece migrate.
All of that is to say: I would not see a JQuery/Angular mix as a final solution, but it can be a good migration strategy.
Upvotes: 1