how to access angular 6 variables in JQuery

Viewed 1811

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

5 Answers

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

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.

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

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.

Related