使用Angular 4 / ionic在模板中显示const

时间:2018-11-20 06:49:36

标签: angular ionic-framework

我在.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>

1 个答案:

答案 0 :(得分:0)

首先,它不能被视为一种实践,因为您做不到。您只能在组件模板中访问组件(public)的属性和方法。

您必须为此在组件上定义一个属性。

...
@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's Official Docs都证明了这一点:

  

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

     

Angular团队负责人Misko Hevery,explains why应该避免复杂的构造方法逻辑。