I have a question about Angular (v4) and external jQuery plugin. I worked with this jQuery plugin before but with asp.net not Angular. My jQuery plugin consists of 3 elements:
<div id="mapsvg"></div>
)$('#mapsvg').mapSvg({source: '/maps/usa.svg'});
)I'm using jQuery plugin from this site: http://mapsvg.com/documentation/jquery/
My question is how can I add this plugin to my Angular project? I tried to do that in new blank project but it does not work.
At this moment I:
"./src/assets/mapsvg/js/mapsvg.js"
declare var $: any;
Right now I receive an error in console that my usa.svg file is not found (404). When I move the svg file into src folder it shows on page but all plugin functionality are not working.
Could anybody please help me with this implementation?
Firstly, You need to install JQuery using npm install jquery --save
and then in your .ts file add import * as $ from "jquery";
This will install jQuery and make it usable. Now , whichever plugin you want, download its source file, keep those files in your assets folder and import that file in your index.html
As, for you, you need to keep this codes in your index.html
<link href="assets/mapsvg.css" rel="stylesheet">
<script type="text/javascript" src="assets/jquery.js"></script>
<script type="text/javascript" src="assets/jquery.mousewheel.js"></script>
<script type="text/javascript" src="assets/mapsvg.min.js"></script>
now add this div file, where you want to implement the plugin as
<div id="mapsvg"></div>
Lastly, call the plugin in ngOnInit() of your component as
$('#mapsvg').mapSvg({source: '"assets/mapsvg.svg"'});
This much should do the trick. For any query, please comment.
Add the dependencies in the angular build configuration. Assuming the app was scaffolded using angular-cli here an example for Angular 6.x and lower versions.
Depending on the version there is an angular / angular-cli configuration file
Angular 6.x -> angular.json
Angular 2.x - 5.x .angular-cli.json (a hidden file)
In both files there is a scripts
section which holds an Array
. Add external dependencies there in the order it would be added for <script>
tags in HTML
.
Then finally add the typings definition for jQuery:
npm install @types/jquery
And use it within your component:
import * as $ from "jquery";
@Component({
selector: 'app-mycomponent',
templateUrl: './mycomponent.component.html',
styleUrls: ['./mycomponent.component.scss']
})
ngOnInit() {
$('#mapsvg').mapSvg({source: '"assets/mapsvg.svg"'});
}
Finally the plugin can be called from ngOnInit method or whenever the <div id="mapsvg"></div>
element appears via method call or on a conditional via *ngIf
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.