angular - 使用 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>
解决方案
首先不能将其视为一种练习,因为您不能这样做。您只能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解释了为什么应该避免复杂的构造函数逻辑。
推荐阅读
- kubernetes - 通过 JenkinsX 部署时,Pod 将进入“Image Pull Back Off”错误
- sql - 在火花中将行转换为列
- macos-catalina - ITerm2 + Mac Catalina + Zsh + Oh My Zsh + Powerline10K -> 没有正确显示字体
- javascript - 将网格居中到页面中心
- ios - 在位置访问弹出 Swift 中检测用户选择
- django - 如何在 Razor Pay 支付网关中获取 order_id?
- javascript - 访问对象中的嵌套键并将它们与其他对象键进行比较,但第二个是对象数组
- azure - 如何将文件从多个源文件夹复制到 Azure Data Lake Storage Gen 2 中的目标文件夹
- mongodb - 如何在 golang 中获取 mongodb 的 int 类型`_id`?
- python - 为什么程序需要这么长时间才能运行?