2017-05-10 78 views
1

Im試圖將timediff變量綁定到組件以進行倒計數。 但我得到如下:無法綁定到'inputDate',因爲它不是'x'的已知屬性。

zone.js:522 Unhandled Promise rejection: Template parse errors: 
Can't bind to 'inputDate' since it isn't a known property of 'countdown'. (" 

      <div *ngIf="countdown > 0"> 
      <countdown [ERROR ->]inputDate="{{timediff}}">{{ timediff | date: 'yMMMdjms' }}</countdown> 
      </div> 


Can't bind to 'inputDate' since it isn't a known property of 'countdown'. (" 

      <div *ngIf="countdown > 0"> 
      <countdown [ERROR ->]inputDate="{{timediff}}">{{ timediff | date: 'yMMMdjms' }}</countdown> 
      </div> 

我怎樣才能使它接受我的變量? timeDiff測量值的

例如:

1494418776073 

HTML:

<countdown inputDate="{{timediff}}">{{ timediff | date: 'yMMMdjms' }}</countdown> 

組件:

import { Component, OnInit, Input, OnChanges, ElementRef, OnDestroy } from '@angular/core'; 
    import { Observable, Subscription } from "rxjs/Rx" 

    @Component({ 
     selector: 'countdown', 
     template: `{{message}}`, 
    }) 
    export class CountdownComponent implements OnInit { 
     private future: Date; 
     private futureString: string; 
     private diff: number; 
     private $counter: Observable<number>; 
     private subscription: Subscription; 
     private message: string; 


     constructor(elm: ElementRef) { 
     this.futureString = elm.nativeElement.getAttribute('inputDate'); 
     } 

     dhms(t) { 
     var days, hours, minutes, seconds; 
     days = Math.floor(t/86400); 
     t -= days * 86400; 
     hours = Math.floor(t/3600) % 24; 
     t -= hours * 3600; 
     minutes = Math.floor(t/60) % 60; 
     t -= minutes * 60; 
     seconds = t % 60; 

     return [ 
      hours + 'h', 
      minutes + 'm', 
      seconds + 's' 
     ].join(' '); 
     } 




     ngOnInit() { 
     this.future = new Date(this.futureString); 
     this.$counter = Observable.interval(1000).map((x) => { 
      this.diff = Math.floor((this.future.getTime() - new Date().getTime())/1000); 
      console.log(x); 
      return x; 
     }); 

     this.subscription = this.$counter.subscribe((x) => this.message = this.dhms(this.diff)); 

     } 
     ngOnDestroy(): void { 
     this.subscription.unsubscribe(); 
     } 


    } 

回答

1

你應該下面的代碼添加到CountdownComponent

@Input() 
inputDate: string; 

,並在模板中,如下使用它:

<countdown [inputDate]="timediff">{{ timediff | date: 'yMMMdjms' }}</countdown> 
+0

的感謝!爲什麼我不再能夠得到inputDate的任何原因? – maria

+0

@maria請參閱https://angular.io/docs/ts/latest/cookbook/component-communication.html – Pengyy

+0

謝謝。接受你的回答。你可以自由地查看我的其他主題,我的問題:) – maria

相關問題