jquery not working in Angular 2?

I have a dynamic dropdown creating by jquery. In Home Component there has a div with id currencyvalue, dropdown will create on it by jquery function that is in common.js and jquery.ddslick.min.js. Jquery loaded before Home component load that's why dropdown is not populated.

So i want to load jquery after home component loaded so jquery function will work.

Code : Home Component

Home Component.ts

import { Component, OnInit } from '@angular/core';

import * as $ from  '../../assets/js/jquery.min.js';
import '../../assets/js/bootstrap.min.js';
import '../../assets/js/jquery.ddslick.min.js';
import '../../assets/js/common.js';

// import * as $ from 'jquery';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    
  }

}

/*      Common.js    */

Common.js

var ddData = [
{
    text: "Bitcoin",
    value: 1,
    selected: true,
    description: "",
    imageSrc: "images/bitcoin-icon.png"
},
{
    text: "Ethereum",
    value: 2,
    selected: false,
    description: "",
    imageSrc: "images/ethereum-icon.png"
},
{
    text: "Dash",
    value: 3,
    selected: false,
    description: "",
    imageSrc: "images/dash-icon.png"
},
{
    text: "Litecoin",
    value: 4,
    selected: false,
    description: "",
    imageSrc: "images/litecoin-icon.png"
}
];

$('#currencyvalue').ddslick({
data: ddData,
width: 190,
imagePosition: "left",
selectText: "Select your Choice",
onSelected: function (data) {
    console.log(data);
}
});
Home Component Html

<div class="col-sm-6">
                                <fieldset>
                                    <label for="selvalue" class="textwhite text-center font16 pb10">Crypto</label>
                                    <div id="currencyvalue">

                                    </div>
                                </fieldset>
                            </div>

1 answer

  • answered 2018-07-11 04:57 Just code

    Wrap your common.js function inside one function lets say like this:

    function InitializeDropdown(){
     $('#currencyvalue').ddslick({
     data: ddData,
     width: 190,
     imagePosition: "left",
     selectText: "Select your Choice",
     onSelected: function (data) {
        console.log(data);
     }
    }
    

    Now, into your HomeComponent use ngAfterViewInit to call this function

    ngAfterViewInit(){
        (window as any).InitializeDropdown()
    }
    

    Remember I have not tested this code.