首页 > 解决方案 > IE11 不在动态表中渲染 DOM 元素

问题描述

使用 Angular 过滤表格数据时,我在 IE11 上遇到了奇怪的行为。

<ng-container *ngFor="let item of items; trackBy: trackByFn">
    <tr>...</tr>
    <tr *ngIf="showDetails(item)">...</tr>
</ng-container>

items发生的情况是,当 IE11 中发生更改(即搜索或过滤数据时)时,某些行未正确呈现:

在此处输入图像描述

正如您在上图中所见,<tr>元素在那里,其内容也在那里。绿色行渲染得很好,但红色行显然不是。只要我悬停空行,它的内容就会再次出现。

该问题可能是由ng-container每两行的包装引起的,IE 无法正确处理此问题。有什么想法可以解决这个问题吗?

标签: angulardomhtml-tablerenderinginternet-explorer-11

解决方案


不幸的是,删除元素中的空格<td>并不能解决问题。但是,我确实设法通过*ngIf仅为 Internet Explorer 创建一个自定义指令来使其工作,这会强制浏览器重新呈现表格:

对于那些遇到同样问题的人,这里是代码:

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

/**
 * Add the template content to the DOM when the condition is true for IE browsers only.
 */
@Directive({
  selector: '[appIfIE]'
})
export class IfIeDirective {

  private hasView = false;
  private isIE = navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > -1;

  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef
  ) {}

  @Input() set appIfIE(condition: boolean) {
    if (!this.isIE && !this.hasView) {
      this.createView();
    } else if (this.isIE && condition && !this.hasView) {
      this.createView();
    } else if (this.isIE && !condition && this.hasView) {
      this.clearView();
    }
  }

  createView() {
    this.viewContainer.createEmbeddedView(this.templateRef);
    this.hasView = true;
  }

  clearView() {
    this.viewContainer.clear();
    this.hasView = false;
  }

}

...并在您认为合适的地方应用指令:

<tbody *appIfIE="!loading">

干杯!


推荐阅读