2017-05-10 66 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

相关问题