toLocaleDateString 在 Angular 运行时动态调用时不是函数

toLocaleDateString is not a function when called dynamically in Angular runtime

我有一个 ActionInstruction 类型的元素数组。 有些是在组件的构造函数中添加的,有些是由用户通过对话框表单域动态添加的。

 actionInstructions: ActionInstruction[];

 constructor(private _formBuilder: FormBuilder, public dialog: MatDialog) {
 this.actionInstructions = [{post_date_start: new Date()}];
 }

 someMethod(){
    // get result of Type ActionInstruction from Dialog -> newInstruction
  this.actionInstructions.push(newInstruction);
 }

数组的内容在视图中显示如下:

<div *ngFor="let actionInstruction of actionInstructions">
      <div *ngIf="actionInstruction.post_date_start"   (click)="openActionCreation(actionInstruction)" class="action-instruction">
         <div class=" fl ml-50">
          Am {{actionInstruction.post_date_start.toLocaleDateString()}}
         </div> 
      </div>
</div>

在开始时,添加到构造函数中的元素可以毫无问题地获得本地化日期。但是通过表单动态添加元素后,会抛出以下错误:

一开始我以为可能是在运行时在视图中调用它引起的,但问题实际上发生在另一个完全独立的组件中,我在其中准备了要在视图中显示的变量,在构造函数中使用相同的功能。

 constructor(){
   if(this.user.birthday != null){
        this.localizedBirthday = this.user.birthday.toLocaleDateString();
    }
  }

这里似乎在错误发生和不发生时几乎没有模式。 这两个组件唯一的共同点是,它们在显示日期的视图组件中使用了一些 *ngIf 模式。

不是直接的解决方案,但您可以在组件中使用日期管道。 https://angular.io/api/common/DatePipe

看起来像这样:

<div class=" fl ml-50">
  Am {{actionInstruction.post_date_start | date:'medium' }}
</div>