11

Im using boostrap-select Dropdown in angular 2 forms with jquery. Onchange jquery event i want to call a Typescript onDropDownChangeChange method. But its not working.

import { Component, OnInit, ViewChild } from '@angular/core';
import { RequestOptions } from '@angular/http';
import 'rxjs/add/observable/throw';
declare var $: JQueryStatic;

export class TestComponent implements OnInit {
  selectedValue: string;

  ngOnInit(): void {

        $(function() {
         var self = this;
          $('.selectpicker').on('change', function(){
            var selectedds = $(this).find('option:selected').val();
            self.onDropDownChangeChange(selectedds); //This is not working
            //this.onChange();
          });

        });  

  }

  onDropDownChangeChange(value: string) {
        this.selectedValue = value;
        this.PopulateGrid(selectedValue);
   }


}
2
  • 2
    what is the point in using jQuery to listen to that event while you can still use ngModel and/or template syntax to achieve this ? Commented May 9, 2017 at 12:26
  • General rule - every time you get tempted to use jQuery in an Angular/React/Vue app, there's a 99.999% chance there's a better way of doing things. Commented May 9, 2017 at 12:28

2 Answers 2

26

You are confusing the scopes. It should be like this:

ngOnInit(): void {

    var self = this;
    $(function() {

          $('.selectpicker').on('change', function(){

              var selectedds = $(this).find('option:selected').val();
              self.onDropDownChangeChange(selectedds); //This is not working
              //this.onChange();

           }); 

    }); 
}
Sign up to request clarification or add additional context in comments.

2 Comments

Ya its working fine now. onDropDownChange event Im populating Grid based on dropdown value. code is executing without any error, But Grid is not loading. Can you please help on this?
@PrabhuArumugam I don't know about Grids, I'm sorry : / you can ask another question about that if this one is resolved tho.
2

You're missing the context.

And to handle 3rd party library custom event, in some case you need tell Angular run your code after received the event like this.

constructor(private zone: NgZone) {}
ngOnInit(): void {
    var self = this;
    this.zone.run(() => {
      $('.selectpicker').on('change', function(){
        var selectedds = $(this).find('option:selected').val();
        self.onDropDownChangeChange(selectedds);
        //this.onChange();
      }); 
    });

  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.