Ronak Gupta
Ronak Gupta

Reputation: 71

How to use Angular 4 variable inside Jquery Function

This question has already got some response here. But this doesn't seem to be working for me.

I am trying to create a tree structure using jQuery. The problem is I can not use a declared angular 4 variable inside a jQuery function. Here's the code.

employees = ["Mr. John", "Mr. Steve"];

ngOnInit() {
   (function($) => {
      function OrgChart($container, opts){
          console.log(this.employees);
      }
   });
}

I see an error in console stating, "Function declarations are not allowed inside blocks in strict mode when targeting ES3 or ES5"

Upvotes: 2

Views: 1037

Answers (2)

Diogo Rodrigues
Diogo Rodrigues

Reputation: 1332

You need store angular component reference in another variable before start jquery block.

export class PlanGruposComponent implements OnInit {
   group = 'Meu grupo';

   OnInit() {

       //reference of currect component object
       let temporaryThis = this; 

       $(document).ready(function () {
          console.log("Print : " + temporaryThis.group);
       });

   }
}

Upvotes: 0

Pac0
Pac0

Reputation: 23174

1st (the employees of undefined problem)

To bind the "this" of the component, use the arrow notation for functions :

($) => { console.log(this.employees)}

instead of function($) { ... }

2nd (the "function declarations are not allowed inside blocks")

You could declare your other inner function in another place in your Angular component, and then refer to it :

ngOnInit() {
    // this declaration is nonsense to me, this will declare a function that is never called and exists only here, but anyway... 
    ($) => {
        // you can call OrgChart here : 
        this.OrgChart()
    } 
}

OrgChart($container, opts) { 
    console.log(this.employees); 
}

Upvotes: 3

Related Questions