【问题标题】:How to get the date time from template into component如何从模板获取日期时间到组件中
【发布时间】:2018-05-30 14:17:28
【问题描述】:

我正在使用 datetime 管道来格式化时间并在模板中显示。但我想在我的组件中获得相同的时间。如何做到这一点?

这里是堆栈闪电战:https://stackblitz.com/edit/angular-sb3ekr

我想使用一些变量来获取 app.component.ts 中显示的日期时间。请告诉我该怎么做?

【问题讨论】:

    标签: angular angular-date-format


    【解决方案1】:

    您可以在组件中使用 DatePipe。

    var tmp = new DatePipe('en-Us').transform(this.today, 'dd:MM:yyyy hh-mm-ss');
    

    【讨论】:

    • 谢谢,这更容易了。
    【解决方案2】:

    我使用 ViewChild 和 ElementRef 解决了这个问题, 这就是我改变的地方,

    HTML,

    <span #dtime> {{ today | date :'dd-MM-yyyy hh:mm:ss'}}</span>
    

    组件,

    today: number = Date.now();
      dateT: string = undefined;
    
    @ViewChild("dtime", {read: ElementRef}) dtime: ElementRef;
    
      ngAfterViewInit(): void {
        this.dateT = this.dtime.nativeElement.textContent;
     // console.log(this.dtime.nativeElement.textContent);
      console.log(this.dateT);
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-09
      • 1970-01-01
      • 1970-01-01
      • 2016-05-13
      • 1970-01-01
      • 2020-06-02
      • 2012-01-12
      相关资源
      最近更新 更多