3

I have a variable in my angular 6 code, I'd like this variable to be set on document ready. How can I use angular var in JQuery?

export class AppComponent implements OnInit {
    public myVar : string = "blue";


  public ngOnInit()
  {
     $(document).ready(function(){
              var ev = $('DivClassName');
              var txt = ev.html();
              if (txt == this.myVar)
              {
                ev.css("background-color", this.myVar); 
                this.myVar = txt;
              }
     });
  } // ngOnInit
}

In this case I get this error in editor: Property 'myVar' does not exist on type 'HTMLElement'.ts(2339)

EDIT: actually, I want to change background-color for each event depends on event-type in my app https://stackblitz.com/edit/angular-q14jh3

vsam
  • 533
  • 3
  • 23
  • 1
    The `this` in `this.myVar` refers to the context of the callback given to `.ready`. – VLAZ Jul 02 '19 at 08:40

5 Answers5

1

You need to bind the correct context, i.e. this to your $(document).ready(function()... function:

$(document).ready(function(){
              var ev = $('DivClassName');
              var txt = ev.html();
              if (txt == this.myVar)
              {
                ev.css("background-color", this.myVar); 
                this.myVar = txt;
              }
     }.bind(this));
ViqMontana
  • 5,090
  • 3
  • 19
  • 54
  • but yet I have this error in my editor : `Property 'myVar' does not exist on type 'HTMLElement'.ts(2339) ` – vsam Jul 02 '19 at 09:01
  • Hmmm, not sure your problem then. See the working StackBlitz example of this [here](https://stackblitz.com/edit/angular-5nwn1z) – ViqMontana Jul 02 '19 at 09:12
  • actually, I want to change background-color for each event depends on event-type in my app https://stackblitz.com/edit/angular-q14jh3 – vsam Jul 02 '19 at 10:00
0
Use callback with Arrow Functions for document ready method.
    export class AppComponent implements OnInit {
        public myVar : string = "blue";


      public ngOnInit()
      {
         $(document).ready(() => {
                  var ev = $('DivClassName');
                  var txt = ev.html();
                  if (txt == this.myVar)
                  {
                    ev.css("background-color", this.myVar); 
                    this.myVar = txt;
                  }
         });
      } // ngOnInit
    }

With ngOnInit document.ready is not executed, so it should be in ngAfterViewInit

    ngAfterViewInit(): void {
           $(document).ready(() => {
                      var ev = $('DivClassName');
                      var txt = ev.html();
                      if (txt == this.myVar)
                      {
                        ev.css("background-color", this.myVar); 
                        this.myVar = txt;
                      }
             });
    }
Kathak Dabhi
  • 399
  • 3
  • 16
  • 1
    No, using arrow syntax will make no difference whatsoever. – Chris Pickford Jul 02 '19 at 08:51
  • @ChrisPickford, Arrow function is working fine, here he had implemented the document ready function in ngInit which is executed before the html view is ready, So if he moved his document.ready function to ``ngAfterViewInit``, arrow function will work with this scope of component – Kathak Dabhi Jul 02 '19 at 09:26
0

You have at least one bug in your code. The document ready is going to be fired, when the page is loaded, but in the Angular ngOnInit method the document is already ready and it will not fire.

The next thing is, you don't need jQuery for this purpose, just use the Angular build in property binding.

I would develop this in the way

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

@Component({
  selector: 'app-bg',
  template: 'blue'
})
export class BgComponent {
  background = 'blue';

  constructor(private elementRef: ElementRef) {}

  @HostBinding('style.background-color') 
  get backgroundColor() {
    return this.elementRef.nativeElement.innerHTML === this.background
      ? this.background
      : null
  }
}

Also have a look at NgStyle.

See this Stackblitz.


You can actually use variables from angular within jQuery, the problem with your code is that the function() {} overwrites your closure. Meaning, the this inside of the function does not refer to the component class anymore. You can prevent that by using the lambda function () => {}. In your code you can simply remove the document ready check, because ngOnInit checks if your component is already initialised.

Felix Lemke
  • 6,189
  • 3
  • 40
  • 67
  • yes I know but I just wanted to show with an example how can I access angular's variables in JQuery – vsam Jul 02 '19 at 08:58
  • 1
    Ah ok, here is a good example for it https://stackoverflow.com/questions/30623825/how-to-use-jquery-with-angular – Felix Lemke Jul 02 '19 at 09:01
  • actually, I want to change background-color for each event depends on event-type in my app [here](https://stackblitz.com/edit/angular-q14jh3) – vsam Jul 02 '19 at 09:49
  • That's exactly what my component does, change the background color depending on the content. – Felix Lemke Jul 02 '19 at 12:37
  • but in your component how can I find specific div tag. As example I have a div tag with class 'event' and I want just to change the background-color for this div – vsam Jul 02 '19 at 12:42
0

Try this

//To use jquery
declare var $: any;

export class AppComponent implements OnInit {

    public myVar : string = "blue";

    public ngOnInit() {

        var ev = $('DivClassName').css("background-color");            

        if (ev == this.myVar){
           ev.css("background-color", this.myVar); 
           this.myVar = ev;
        }
    }
}
hrdkisback
  • 898
  • 8
  • 19
-1

You have a bug.

First of all,when OnInit function is called- the document is ready.

Besides, you should avoid using jQuery and angular together.

see Here.

tamar
  • 132
  • 4