调用组件时定义变量

Define variable when calling component

我需要将日期定义为组件的 @Input:

<progress [start]="new Date()"></progress>

我收到这个错误:

Parser Error: Unexpected token 'Date' at column 5 in [new Date()]

调用组件时如何定义变量值?

您不能 create/initialise 并在属性内部赋值。

HTML

<progress [start]="getDate()"></progress>

Class

getDate(){
  return new Date()
}

这就是说,您可能不想以这种方式使用它,因为这样会通过更改检测生成新的日期。您可能希望将属性的值保留在 属性:

Class

myDate= new Date(); // This could be either on the top of the class, either in ngOnInit. Avoid putting in the constructor

HTML

<progress [start]="myDate"></progress>

您必须在 component.ts 中初始化您的日期,例如在 ngOnInit 中:

myDate: Date;

ngOnInit() {
    this.myDate = new Date();
}

并在您的模板中使用它:

<progress [start]="myDate"></progress>