简体   繁体   English

单击同级组件中的按钮时,如何暂停/恢复计时器?

[英]How do I pause/resume a timer when a button from sibling component is clicked?

I am new to Angular. 我是Angular的新手。 How do i send a message between siblings component? 我如何在兄弟姐妹组件之间发送消息? For example, one of my component has a timer. 例如,我的组件之一有一个计时器。 The silbling component has a stop button. 兄弟组件具有一个停止按钮。 When this button is clicked, i want to pause the timer. 单击此按钮时,我想暂停计时器。

My component with a timer: 我的组件带有计时器:

import { Component, OnInit } from '@angular/core';

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

  public this.time: number = 0;
  public uiTimerId;

  constructor() { }

  private timer(): void {
    ++this.time;
  }

  ngOnInit() {
    this.start = new Date().getTime();

    this.uiTimerId = window.setInterval(this.updateTimer.bind(this), 1000);
  }



}

My timer html: 我的计时器html:

{{ time }}

The Parent component html: 父组件html:

<app-header></app-header>
<app-test></app-test>

My other component (silbling) 我的其他组件(银)

<nav>
  <button>Pause Timer here</button>
</nav>

在服务中使用一个主题,然后在组件中对其进行订阅以查看其单击时间。

I'm using EventEmitter and subscribe to it to change the start/stop time. 我正在使用EventEmitter并订阅它来更改开始/停止时间。 When a sibling component click stop button, it will call the method in service which emit the EventEmitter. 当同级组件单击停止按钮时,它将调用服务中的方法,该方法将发出EventEmitter。 The TestComponent will subscribe to this EventEmitter value and stop the time. TestComponent将订阅此EventEmitter值并停止时间。

I create a demo for you 我为您制作一个演示

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

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