在一个组件上运行按钮,在另一个组件上显示性能

时间:2019-12-16 21:29:48

标签: angular typescript

我开发了运行计时器的服务,一切正常。

在创建计时器的组件上运行计时器时,是否还可以在其他组件上查看其正常工作?

尝试过,但是没有用:(

@Input() button: boolean = false;

<p *ngIf="button">{{servicesService.fetchDisplay()}}</p>

<app-services [button]="true"></app-services> 

所有服务组件都出现在另一个组件中,但是计时器不起作用。

服务

  startTimer() {
    this.interval = setInterval(() => {
      if (this.time === 0) {
        this.time++;
      } else {
        this.time++;
      }
      this.display = this.transform(this.time);

      return this.display;
    }, 1000);
  }

HTML

<button (click)='startTimer()'>Start Timer</button>
<button (click)='pauseTimer()'>Pause</button>
<p >{{servicesService.fetchDisplay()}}</p> 

1 个答案:

答案 0 :(得分:1)

您还需要将服务添加到“关于”组件中[将其保留在另一个组件中,以从两个位置控制计时器],就像这样:

import { Component, OnInit } from '@angular/core';
import { ServicesService } from '../services/services.service';
@Component({
  selector: 'app-about',
  templateUrl: './about.component.html',
  styleUrls: ['./about.component.css']
})
export class AboutComponent implements OnInit {

  constructor(private servicesService: ServicesService) { }

  ngOnInit() {
  }
 startTimer() {
    this.servicesService.startTimer();
  }

  pauseTimer() {
    this.servicesService.pauseTimer();
  }
}
.container {
  width: 100%;
  height: 400px;
  border: solid blue 2px;
  border-radius: 5px;
}
<div class="container" > 
  <h1> This is the about component </h1>
  <h3> Click on Home for instructions </h3>
  <p >{{servicesService.fetchDisplay()}}</p> 
<button (click)='startTimer()'>Start Timer</button>
<button (click)='pauseTimer()'>Pause</button>

</div>

<!-- <app-services [button]="true"></app-services>  -->

enter image description here

相关问题