how to access angular 6 variables in JQuery [duplicate]

问题: This question already has an answer here: How to access the correct `this` inside a callback? 10 answers I have a variable in my angular 6 code, I'...

问题:

This question already has an answer here:

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


回答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));

回答2:

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.


回答3:

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

回答4:

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

回答5:

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.

  • 发表于 2019-07-07 19:47
  • 阅读 ( 615 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除