简体   繁体   中英

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"

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); 
}

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);
       });

   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM