Access angular2 variables in jquery

I use jQuery for some things in my angular2 projects. But I can't use variables declared in angular2 for use in jQuery. I have something like this:

export class AddExerciseComponent implements OnInit {

  parameters:Array<string> = ["FU"];

  constructor() { }

  ngOnInit() {


    $('.chips').on('chip.add', function(e, chip){
      this.parameters.push(chip.data);
      console.log(this.selectedValue);
    });
}

This will give me an error that the parameters are not defined. I guess because I use this. What else can I do?

+4
source share
2 answers

You need to use an arrow function function expression ( () => {}) to save thisin scope. Try:

export class AddExerciseComponent implements OnInit {

parameters:Array<string> = ["FU"];

constructor() { }

ngOnInit() {
// removed function keyword and added () => {} syntax
  $('.chips').on('chip.add', (e, chip) => {  
    this.parameters.push(chip.data);
    console.log(this.selectedValue);
  });
}

, JavaScript , this , . , this , .

+17

angular jquery animate ON-Complete, , :

$('#myDiv').animate({top: 70+"%"},{

  queue: false,
  duration: 1000,
  complete: () => {  

  //this is you angular variable of the class
      this.angularVar = 0;
      $("#myDiv").hide();

  //this is you angular variable of the class    
      this.showAnimation = false;

  //this is you angular class function
      this.angularFunction();

      console.log("animation complete");
  }
});
0

Source: https://habr.com/ru/post/1656123/


All Articles