項目中遇到倒計時需求,考慮到以后在其他模塊也會用到,就自己封裝了一個組件。便于以后復用。
組件需求如下: 
- 接收父級組件傳遞截止日期 
- 接收父級組件傳遞標題
組件效果

變量

組件countdown.html代碼
<div class="count-down">  <div class="title">    <h4>      {{title}}    </h4>  </div>  <div class="body">    <div class="content">      <div class="top">        {{hour}}      </div>      <div class="bottom">        小時      </div>    </div>    <div class="content">      <div class="top">        {{minute}}      </div>      <div class="bottom">        分鐘      </div>    </div>    <div class="content">      <div class="top">        {{second}}      </div>      <div class="bottom">        秒      </div>    </div>  </div></div>組件countdown.scss代碼
.count-down{  width:100%;  height:100px;  background: rgba(0,0,0,0.5);  padding: 2px 0;  .body{    margin-top: 8px;    .content{      width:29%;      float: left;      margin: 0 2%;      .top{        font-size: 20px;;        line-height: 30px;        color: black;        background: white;        border-bottom: 2px solid black;      }      .bottom{        font-size: 14px;        line-height: 20px;        background: grey;      }    }  }}組件countdown.component.ts代碼
import { Component, OnInit, Input, OnDestroy, AfterViewInit } from '@angular/core';@Component({ selector: 'roy-countdown', templateUrl: './countdown.component.html', styleUrls: ['./countdown.component.scss']})export class CountdownComponent implements AfterViewInit, OnDestroy { // 父組件傳遞截止日期 @Input() endDate: number; // 父組件傳遞標題 @Input() title: string; // 小時差 private hour: number; // 分鐘差 private minute: number; // 秒數差 private second: number; // 時間差 private _diff: number; private get diff() {  return this._diff; } private set diff(val) {  this._diff = Math.floor(val / 1000);  this.hour = Math.floor(this._diff / 3600);  this.minute = Math.floor((this._diff % 3600) / 60);  this.second = (this._diff % 3600) % 60; } // 定時器 private timer; // 每一秒更新時間差 ngAfterViewInit() {  this.timer = setInterval(() => {   this.diff = this.endDate - Date.now();  }, 1000); } // 銷毀組件時清除定時器 ngOnDestroy() {  if (this.timer) {   clearInterval(this.timer);  } }}使用方法demo.html
<roy-countdown title="距離考試還有:" [endDate]="endDate"></roy-countdown>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答