【问题标题】:CSS styles doesn't work for Html added by innerHtml in Angular 2+ directiveCSS 样式不适用于 Angular 2+ 指令中由 innerHtml 添加的 Html
【发布时间】:2020-09-08 08:12:06
【问题描述】:

我正在尝试实现一个简单的加载图标指令:

import { Directive, ElementRef, Renderer2, Input, OnChanges } from '@angular/core';

@Directive({
  selector: '[appLoading]',
})
export class LoadingDirective implements OnChanges {
  @Input() appLoading: boolean;

  constructor(private elRef: ElementRef, private renderer: Renderer2) {
  }

  ngOnChanges() {
    if (this.appLoading) {
      this.renderer.addClass(this.elRef.nativeElement, 'loading-wrap');
      this.elRef.nativeElement.innerHtml = '<div class="lds-ellipsis"><div></div><div></div><div></div><div></div></div>';

    } else {
      this.renderer.setStyle(this.elRef.nativeElement, 'display', 'none');
    }
  }

}

在我的模板中我有:

<div [appLoading]="isLoading"></div>

但是对于添加到 innerHtml 中的内容,看起来 Angular 并没有应用我的样式来加载 style.css 中的微调器。不过,这些样式适用于具有“loading-wrap”类的主元素。

【问题讨论】:

  • 您的意思是 lds-elliosis 类样式未应用于 innerHTML div?
  • @Chellappanவ 是的,样式不适用于 lds-ellipsis,但是,它们适用于 loading-wrap 类
  • 抱歉,重播晚了,您能否将 ids-ellipsis 类移至 style.css 并检查

标签: javascript angular angular-directive


【解决方案1】:

错误是innerHtml引起的,显然应该是innerHTML

this.elRef.nativeElement.innerHTML = '<div class="lds-ellipsis"><div></div><div></div><div></div><div></div></div>';

【讨论】:

    最近更新 更多