【问题标题】:Conditional class with condition in a function leads to 'ExpressionChangedAfterItHasBeenCheckedError'函数中带有条件的条件类导致“ExpressionChangedAfterItHasBeenCheckedError”
【发布时间】:2019-08-03 05:42:00
【问题描述】:

我在组件的列表中显示了一组项目。该项目的属性之一是描述字段,其范围可以从一个单词到几个句子。

当描述太长时,我想截断它并显示一个按钮,单击该按钮会显示全文。是否截断并显示按钮的条件是基于这个返回布尔值的函数:

checkOverflow(element) {
  if (element.offsetHeight < element.scrollHeight ||
    element.offsetWidth < element.scrollWidth) {
    return true;
  } else {
    return false;
  }
}

然后我像这样从组件的模板端使用这个函数(ngFor 的一小部分):

 <p #refDescription
    class="item-description--max-height"
    [class.fade--read-more]="checkOverflow(refDescription)">
        {{item.description}}
 </p>
 <button class="button button--read-more" *ngIf="checkOverflow(refDescription">Read more</button>

这里使用的 CSS 很简单:

.item-description--max-height {
  font-size: 20px;
  @include font-fira-sans-italic;
  line-height: 28px;
  margin-bottom: 0;  
  max-height: 2.9em;
  overflow: hidden;
}

.fade--read-more {
  height: 2.9em; /* exactly two lines */
}

目前这种行为非常偶然,我在控制台中收到错误:

ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。以前的值:'ngIf: false'。当前值:'ngIf: true'。

我相信我在将类绑定到函数方面走错了路 - 非常感谢任何建议。我正在使用 Angular 版本 7。

谢谢。

【问题讨论】:

  • 你修好了吗?

标签: angular


【解决方案1】:

这个错误通常是由模板内部调用的方法引起的。

尝试将 checkOverflow() 调用移动到组件中:

// use view children to get references to dom elements
@ViewChildren('refDescription') descRef: QueryList<ElementRef>;

ngAfterViewInit(): void {
  // wait when dom rendered
  setTimeout(() => {
    // get dom elements
    const elements = this.descRef.toArray().map(i => i.nativeElement);
    // check overflow and put result into 'overflow' property
    elements.forEach((el, index) => {
      this.items[index]['overflow'] = this.isOverflow(el); 
    });
  });
}

相应地更新模板:

<p #refDescription
    class="item-description--max-height"
    [class.fade--read-more]="item.overflow">
        {{item.description}}
 </p>
 <button class="button button--read-more" *ngIf="item.overflow">Read more</button>

【讨论】:

  • 这对我有用。 setTimeout 电话至关重要。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-09
  • 2019-04-26
  • 2017-05-12
  • 2017-07-09
相关资源
最近更新 更多