滑稽的下午--angularjs 2.0管道的使用


雖然angular 已經迎來4.0時代,可我還在苦逼的看2.0。

下午有個任務:

  

讓一個component組件里的時間顯示當前時間並自動刷新。

過程:

 1.首先獲取當前時間 new Date();

    2.弄個定時器隔一秒刷新呀;

開工:

app.component.ts中這樣寫到:

InitialTime=new Date();  //獲取當前時間 
 data:string;
  getTime(m){  //判斷獲取的分鍾數是否小於10,小於10只會顯示一位數,前面自動補0
      if(m<10){
         m="0"+m;
        this.data=this.InitialTime.getHours()+":"+m;   //顯示時間(小時+分鍾) eg   17:15
    }
    else{
        this.data=this.InitialTime.getHours()+":"+this.InitialTime.getMinutes();     //顯示時間(小時+分鍾) eg   17:15
    } 
  }
  constructor(){
     this.getTime(this.InitialTime.getMinutes()); //運行上面方法讓時間顯示
     setInterval(()=>{  //設置定時器,隔1秒刷新一次,好實時監控時間
              this.InitialTime=new Date();
              this.getTime(this.InitialTime.getMinutes());                              
              },1000);                
     } 
app.component.html中這樣寫:
 
<span class="time"> {{ date }}</span>
然后變成我想要的效果了,可是代碼我自己都嫌長,而且還是用傳統js方法寫的。后來就想不是angular里面有Pipe管道嗎,是不是可以試試。
再開工: 
app.component.ts是這樣寫的。
time:any=Date.now();  //獲取當前時間
  constructor(){
     setInterval(()=>{  //設置定時器,隔1秒刷新一次,好實時監控時間
           //  this.birthday = new Date();      
           this.time=Date.now();   //Date里面自帶方法                  
               },1000);  
  }
app.component.html是這樣寫的:
  
 <span class="time"> {{time | date:"HH:mm" }}</span>
|是管道標示符。angular里面提供了內置的datePipe管道可以供我們使用
HH:mm 表示輸出小時和分鍾;yy:MM:dd  表示輸出年月日
詳情可以看看官網的管道介紹里面關於DatePipe Api的介紹。
同樣的效果,代碼量就大大減少,所以學習還是在完成的基礎上多嘗試。耶~~~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM