Angular 2 Component自定义属性在构造函数中为null

Angular 2 Component custom attribute is null in constructor

本文关键字:null 构造函数 Component 自定义属性 Angular      更新时间:2024-03-07

我创建了一个组件,并试图在上面发送一个自定义属性。但在构造函数中,我只得到了一个null。我知道它有一些东西,因为我正在打印变量。

这是我实例化倒计时组件的html,我从其他组件调用:

this is how I know voteDate has something{{voteDate}}
<countdown [attr.inputDate]="voteDate"></countdown>

这就是组件(我在构造函数中得到一个null):

import {Component, OnInit, ElementRef} from 'angular2/core';
import {Observable} from 'rxjs/Rx';
@Component({
    selector: 'countdown',
    template: `
  <div class="font-poll-countdown">
    Poll Will Close in: {{message}}
  </div>
`
})
export class CountDown implements OnInit {
    private future: Date;
    private futureString: string;
    private diff: Date;
    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 [
            days + 'd',
            hours + 'h',
            minutes + 'm',
            seconds + 's'
        ].join(' ');
    }

    ngOnInit() {
        this.future = new Date(this.futureString);
        Observable.interval(1000).map((x) => {
            this.diff = Math.floor((this.future.getTime() - new Date().getTime()) / 1000);
        }).subscribe((x) => {
            this.message = this.dhms(this.diff);
        });
    }
}

我尝试了所有的东西,但控制器中仍然为空。

您可以使用InputMetadata,在这里您可以通过属性传递数据。Angular在更改检测期间自动更新数据绑定属性,并将其传递给countdown组件。

用CCD_ 4包装CCD_ 3(将其作为属性传递)&然后要访问该值,您需要在组件内部将其定义为@Input

<countdown [inputDate]="voteDate"></countdown>
//inside your component
@Input() inputDate: Date;

您的自定义属性在构造函数中不可用。您需要等待ngOnInit()生命周期挂钩被调用:

ngOnInit() {
   console.log(this.elm.nativeElement.getAttribute('inputDate'))
}

也就是说,我喜欢@Pankaj的答案——使用属性绑定。然后,如果您愿意,您可以将日期作为实际的JavaScriptDate对象传入。对于属性,您总是会得到一个字符串值。