【问题标题】:Angular div innerHTML from typescript function calling multiple times来自打字稿函数的Angular div innerHTML多次调用
【发布时间】: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;
  }
  1. *ngIf 在函数中不起作用:&lt;div *ngIf="${calendarDate['price']}" class='fare'&gt;${calendarDate['price']}&lt;/div&gt; 错误价格未定义(忽略 *ngIf)。我怎么会写这个?

  2. 当我单击 div 以使该容器可用并启动该函数时,它将调用该函数并因此多次调用 console.log("RENDER Calendar")。是否有任何我不知道并导致多次调用该函数的行为问题?

  3. 由于价格是后期动态增加的,类似的问题没有更好的解决方案吗?尤其是当数组有将近 600 个日期要渲染时(并监听 ngIf 价格和 date_is_valid 的变化。)

【问题讨论】:

  • 为什么不在 HTML 模板中这样做,而不是在代码中构建 HTML?
  • 这不是 REACT - 在 Angular 中,我们将 html、js 和 css 代码分开(每种类型的代码应该在单独的文件中) - 切勿混合使用 - 这是一些教程 angular.io/guide/forms(在你会在底部找到文件)

标签: angular typescript


【解决方案1】:

您的问题的简单示例 https://stackblitz.com/edit/angular-2u6pgj

没有实现您需要的“月”块,因为只是想向您展示 Angular 如何处理它,以及 *ngIf 的工作原理,这就足够了。

您似乎误解了 Angular 处理 Model 和 View 的方式,View 不是由 Model 动态“构建”的,而是与 Model 同步数据。请查看其Architecture Ovreview

【讨论】:

  • 谢谢,我有这个和你的例子一样的方法,但我之所以试图把它放在函数下的决定是因为我认为这是把它分开几个月的最好方法。在html 我没有看到任何解决方案(如何根据某些条件包装循环)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-05
  • 1970-01-01
  • 2021-11-23
  • 2012-11-13
  • 2022-01-24
  • 1970-01-01
相关资源
最近更新 更多