Angular 2 setInterval问题

时间:2017-09-21 06:26:36

标签: angular angular2-directives

当设置间隔执行时,绑定的html输入每秒丢失焦点。我无法打字。但是当我评论设置区间代码时它工作正常。你能帮我朋友吗?

countdown(){

        if (this.seconds <= 0) return;   

        this.countdownInterval = setInterval(()=> {
          if (this.seconds <= 0) {
        clearInterval(this.countdownInterval);

        this.toFinishNotify();       

      }
      this.seconds--;

    }, 1000);
  }

    htmlElement function return input text box <p [innerHtml]="htmlElement(obj) " > </p>

例如

在用户dash点击提交时停止计时器dashdash可以转换为文本框

1 个答案:

答案 0 :(得分:1)

试试这样:

html文件

<input type="text" id="timer">

<强> component.ts

export class AppComponent implements OnInit {

    countdownInterval: any;
    seconds: number = 30;

    constructor(private elementRef: ElementRef) { }

    ngOnInit() {
        var display = this.elementRef.nativeElement.querySelector('#timer');
        this.countdown(display);
    }

    countdown(display) {

        if (this.seconds <= 0) return;

        this.countdownInterval = setInterval(() => {
            if (this.seconds <= 0) {
                clearInterval(this.countdownInterval);
                this.toFinishNotify();

            }
            display.value = this.seconds;
            this.seconds--;

        }, 1000);
    }

    toFinishNotify() {
        console.log('toFinishNotify');
    }
}