【问题标题】:How to access the ::after pseudo selector using ElementRef in Angular如何在 Angular 中使用 ElementRef 访问 ::after 伪选择器
【发布时间】:2019-03-24 12:03:15
【问题描述】:

例如,怎么可能?访问并设置下面元素的 ::after 伪选择器的背景颜色?

@ViewChild('infobubble', { read: ElementRef }) infoBubbleElement: ElementRef;

  ngAfterViewInit(): void {
    const elem = this.infoBubbleElement.nativeElement;
    elem.style.backgroundColor = 'green';
  }

【问题讨论】:

标签: css angular css-selectors


【解决方案1】:

我遇到了同样的情况,无法从 elementRef 访问 ::before 或 ::after HTML 元素;我的解决方案是在我需要访问的 HTML 元素中创建另一个 DIV,用指令修改它并更改 div 的背景,这将是新的 :: before

我的指令示例:

@Directive({selector: '[appPrimaryColor]'})

export class PrimaryColorDirective implements OnInit {

  @Input() backgroundColor = false;

  constructor(
    private elementRef: ElementRef,
    private _renderer: Renderer2,
  ) { }

  ngOnInit() {
    // Set BackgroundColor
    if (this.backgroundColor) {
      this._renderer.setStyle(this.elementRef.nativeElement, 'background-color', COLOR);
    }
  }
}

在 HTML 中:

<div class="icon">
  <!-- step-ok-effect is the new div-->
  <div
    appPrimaryColor
    [backgroundColor]="true"
    class="step-ok-effect"></div>
    <span class="icon-{{ step.state ? 'check' : step.icon }}"></span>
  </div>
</div>

【讨论】:

    猜你喜欢
    • 2021-09-03
    • 1970-01-01
    • 2015-09-18
    • 2018-12-26
    • 2017-08-23
    相关资源
    最近更新 更多