Button的事件监听器不会改变Angular中的类字段

时间:2018-06-05 11:28:53

标签: javascript angular typescript addeventlistener

我想做什么:

  • 生成随机数

  • 计时器计入此数字,然后显示带有随机边距的按钮

  • 第一个计时器停止,第二个计时器启动

  • 当用户点击按钮时,第二个计时器会打印按钮外观和点击之间经过的时间

我想创建一个布尔值的组件类字段,当单击该按钮时,布尔值变为true,然后每个tick的计时器检查布尔值,如果为true,则删除按钮并启动第一个再次计时器。

问题是当我点击按钮时,点击的字段不会改变。这里的问题是什么?

import { Component, OnInit } from '@angular/core';
import {TimerObservable} from "rxjs/observable/TimerObservable";


@Component({
  selector: 'app-gra',
  templateUrl: './gra.component.html',
  styleUrls: ['./gra.component.css']
})
export class GraComponent implements OnInit {

  randNum: any;
  timerSub: any;
  userTimerSub: any;
  clicked: boolean;


  constructor() { }

  ngOnInit() {
    this.randNum = 3+ Math.floor(Math.random()*3);
    console.log('random: ' + this.randNum)
    this.clicked = false;
    let timer = TimerObservable.create(0, 1000);
    this.timerSub = timer.subscribe( d => this.timerFunction(d) );
  }

  timerFunction(d){
    console.log(d);

    if(d === this.randNum){

      var btn = document.createElement("BUTTON");        // Create a <button> element
      var t = document.createTextNode("CLICK ME");       // Create a text node

      btn.appendChild(t);
      btn.id = "button"

      let margin  = Math.floor(Math.random()*500);

      document.body.appendChild(btn);                    // Append <button> to <body>
      btn.setAttribute('style', 'margin-top: ' + margin + "px;");
      document.getElementById("button").addEventListener("click", this.buttonClick);

      this.timerSub.unsubscribe();

      let timer = TimerObservable.create(0, 1000);
      this.userTimerSub = timer.subscribe( d => this.userTimerFunction(d) );
      this.randNum = 3 + Math.floor(Math.random()*3);
      console.log('new rand: ' + this.randNum)
    }
  }

  userTimerFunction(d){
    console.log('user' + d)
    console.log(this.clicked)
    if(this.clicked == true){
      console.log('It took you ' + d + 'seconds');

      this.userTimerSub.unsubscribe();
      var element = document. getElementById("button");
      element.parentNode.removeChild(element);

      let timer = TimerObservable.create(0, 1000);
      this.timerSub = timer.subscribe( d => this.timerFunction(d) );
    }
  }

  buttonClick(){
    console.log('clicked: ' + this.clicked);
    this.clicked = true;
  }
}

1 个答案:

答案 0 :(得分:2)

我相信用你的方式绑定点击方法不会绑定&#39;这个&#39;关键字以您期望的方式和“点击”关键字财产不会改变。您可以尝试使用fat arrow syntax to bind the 'this' keyword

addEventListener("click", () => this.buttonClick())

但是,如果您想在Angular中工作,我建议您使用内置于渲染器service for handling dom manipulations的Angulars。

this.renderer.listen(elementRef.nativeElement, 'click', (evt) => {
    console.log('Clicking the document', evt);
})