【发布时间】:2019-04-09 16:32:17
【问题描述】:
我有一组对象,其中包含大约 2 年的日期、价格(价格在 API 调用之后动态添加)和可以在 Angular 应用程序中更改的验证:
calendarArrayDates = [
{"date": "2018-10-23", "price":"2313", "date_is_valid": true},
{"date": "2018-10-24", "price":"2313", "date_is_valid": true},
...
{"date": "2018-11-01", "price":"2313", "date_is_valid": false},
...
{"date": "2019-02-01", "price":"2313", "date_is_valid": true}
]
我想将这些日期动态显示为日历视图,因此我在我的 component.html 中创建了这个 div:
<div [innerHTML]="renderHTMLCalendar()"></div>
调用这个函数:
renderHTMLCalendar(){
console.log("RENDER Calendar");
let container = "";
for (var calendarDate of this.calendarArrayDates) {
var date = calendarDate['date'];
var mDate = moment(date)
if (date === mDate.startOf('month').format(CALENDAR_DEFAULT_FORMAT)) {
container = "<div class='month'>"
}
container += `<div>
<div class='day'>${calendarDate['date']}
<div *ngIf="${calendarDate['price']}" class='price'>${calendarDate['price']}</div>
</div>`;
if (mDate === mDate.endOf('month')) {
container += "</div>"
}
}
return container;
}
*ngIf 在函数中不起作用:
<div *ngIf="${calendarDate['price']}" class='fare'>${calendarDate['price']}</div>错误价格未定义(忽略 *ngIf)。我怎么会写这个?当我单击 div 以使该容器可用并启动该函数时,它将调用该函数并因此多次调用 console.log("RENDER Calendar")。是否有任何我不知道并导致多次调用该函数的行为问题?
由于价格是后期动态增加的,类似的问题没有更好的解决方案吗?尤其是当数组有将近 600 个日期要渲染时(并监听 ngIf 价格和 date_is_valid 的变化。)
【问题讨论】:
-
为什么不在 HTML 模板中这样做,而不是在代码中构建 HTML?
-
这不是 REACT - 在 Angular 中,我们将 html、js 和 css 代码分开(每种类型的代码应该在单独的文件中) - 切勿混合使用 - 这是一些教程 angular.io/guide/forms(在你会在底部找到文件)
标签: angular typescript