首页 > 解决方案 > 使用 Angular 4 / ionic 在模板中显示 const

问题描述

我在 .ts 文件的构造函数中声明了常量。我想在模板中显示它们的值。

这是好的做法吗?

编辑:

import {Component, OnInit, Output} from '@angular/core';
import { NavController } from 'ionic-angular';
import {MemoryEditPage} from "../memory-edit/memory-edit";


@Component({
    selector: 'page-memory-list',
    templateUrl: 'memory-list.html',
})
export class MemoryListPage implements OnInit {

    @Output() k_user: string;
    @Output() type: MemoryType = MemoryType.memories;


    constructor(
        private auth: AuthService,
        public navCtrl: NavController,
    ) {
        const monthNames = ['Janvier','Février','Mars','Avil','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre'];
        const thisMonth = monthNames[(new Date()).getMonth()];
        const dayNames = ['Lun','Mar','Mer','Jeu','Ven','Sam','Dim'];
        const thisDay = dayNames[(new Date()).getDay() - 1];
        const thisDate = (new Date()).getDate();

        this.thisDay = thisDay;
        this.thisDate = thisDate;
        this.thisMonth = thisMonth;

    }


}

模板:

<ion-label no-margin text-uppercase color="white">{{thisMonth}}</ion-label>

标签: angularionic-framework

解决方案


首先不能将其视为一种练习,因为您不能这样做。您只能public在组件的模板中访问组件的 ( ) 属性和方法。

为此,您必须在 Component 上定义一个属性。

...
@Component({...})
export class MemoryListPage implements OnInit {

    ...
    thisMonth;

    constructor(...) {
        ...
        const thisMonth = monthNames[(new Date()).getMonth()];
        this.thisMonth = thisMonth;
        ...
    }
}

然后在您的模板中使用它:

<ion-label 
  no-margin 
  text-uppercase 
  color="white">
  {{thisMonth}}
</ion-label>

更新:

回答您更新的问题,在constructor. 它应该写在ngOnInit. 甚至Angular 的官方文档也证明了这一点:

经验丰富的开发人员同意组件应该便宜且构建起来安全。

Angular 团队负责人 Misko Hevery解释了为什么应该避免复杂的构造函数逻辑。


推荐阅读