繁体   English   中英

Button的事件侦听器不会更改Angular中的类字段

[英]Button's event listener doesn't change class field in Angular

我正在尝试做的是:

  • 产生一个随机数

  • 计时器计数到该数字,然后显示带有随机余量的按钮

  • 第一个计时器停止,第二个计时器开始

  • 当用户单击按钮时,第二个计时器打印按钮外观和单击之间经过了多少时间

我想创建一个布尔类型的组件类字段,然后单击按钮时,布尔值将更改为true,然后每个刻度线的计时器都会检查布尔值,如果为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;
  }
}

我相信,以您的方式绑定click方法不会像您期望的那样绑定'this'关键字,并且'clicked'属性也不会改变。 您可以尝试使用粗箭头语法绑定'this'关键字

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

但是,如果要在Angular中工作,我建议您使用内置的渲染器服务中的 Angulars 处理dom操作

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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