Dimitris Kounarakis
Dimitris Kounarakis

Reputation: 13

Using jQuery along custom javascript files in angular 6

I have this myjs.js file

function slide_down(id) {
    $('#' + id).slideToggle();
}
function open_team_info(id) {
    $('#team-info-' + id).css("visibility", "visible");
    $('#team-info-' + id).css("opacity", "1");
}
function close_team_info(id) {
    $('#team-info-' + id).css("visibility", "hidden");
    $('#team-info-' + id).css("opacity", "0");
}

I want to use this functions in terms of

(click)=a_function('someID')

in HTML

How can I include this functions in my component from myjs.js file?

In other words, is there any relevant solution as we do in plain HTML project like:

<script src="myjs.js"></script> 

PS: I got 5 days with Angular so any Hint or suggestion will do

Upvotes: 0

Views: 797

Answers (3)

ssz
ssz

Reputation: 337

If you used Angular-Cli so you have an angular.json file in root directory of the project and you can import custom styles and script files into your project by referencing them in this file. for example for script files you should write the path to the file in "script" section:

"scripts": [
  "node_modules/jquery/dist/jquery.min.js",
  "node_modules/bootstrap/dist/js/bootstrap.js",
  "PathToFile/myjs.js"
]

Upvotes: 0

esakki
esakki

Reputation: 153

Normally jquery is not preferable in angular. Instead You can simply use

class binding or style binding in angular. if you need you can simple declare the jquery element in your component

declare var $: any

for example in your div tag use like this

<div [style.visibilty] = "visible">
</div>

or

<div [ngStyle] = "myclass">
</div>

and in your ts file you can make a binding option

visible = "hidden";
myclass = {
   "visibility" : this.visible,
}

if you are using seprate file for these scripts means you can use import option to use the the file

import { examplefunction } from '../../service/myjs.ts';

Upvotes: 0

Tu Nguyen
Tu Nguyen

Reputation: 10179

If you used the Angular-Cli to create the Angular Project. Then you could create an myjs.ts file inside the src folder.

Then, in order to use those function, you have to export them first, like this:

export function fslideDown(id) {
  $('#' + id).slideToggle();
}
export function open_team_info(id) {
  $('#team-info-' + id).css('visibility', 'visible');
  $('#team-info-' + id).css('opacity', '1');
}
export function close_team_info(id) {
  $('#team-info-' + id).css('visibility', 'hidden');
  $('#team-info-' + id).css('opacity', '0');
}

Inside any component file, you may import them like this:

import { close_team_info, fslideDown, open_team_info } from '../../myjs';

Then using it as normal functions.

Hopefully, it works as expected.

Upvotes: 1

Related Questions