【问题标题】:DOM Manipulations in Angular 5Angular 5 中的 DOM 操作
【发布时间】:2018-12-13 17:12:12
【问题描述】:

例如我有:

<div class="btn-wrapper-bt1"> <button>AAA</button> </div>

此按钮位于node_modules/somebt 中存在的第 3 方元素上

我想在 Angular 环境中做一些简单的类更改。

ngOnInit有没有简单的修改方法?还是我需要 fork 源并在源中进行更改?

提前致谢。

【问题讨论】:

  • 为什么不使用 ngClass ?
  • 你试过::ng-deep吗?
  • @DanielHoppeAlvarez 无法使用 ngClass 因为我无法访问 HTML 或元素的代码 - 它是第 3 方组件
  • @ibenjelloun 相同 - 无法访问组件。
  • 你只需使用 CSS 覆盖样式

标签: javascript angular dom


【解决方案1】:

在 html 中,添加 #ref 对包含您的第 3 方组件的元素的引用

yourComponent.html

<div #ref >
   <your-3rd-party-component></your-3rd-party-component>
</div>

然后,在您的组件中,检索包含元素的子元素

yourComponent.ts

import { Component,Renderer2, ViewChild,ElementRef } from '@angular/core';

export class YourParentComponent  {


  @ViewChild('ref') containerEltRef: ElementRef;

  constructor(private renderer: Renderer2)
  {

  }

  ngAfterViewInit()
  {
    // retrieves element by class 
    let elt = this.containerEltRef.nativeElement.querySelector('.btn-wrapper-bt1');
    this.renderer.addClass(elt, 'newClass'); //Adds new class to element

  }
}

这是stacklblitz demo

注意:如果你只是想改变第三方组件的外观,你可以在你自己的组件中重写类

yourComponent.scss

:host ::ng-deep .btn-wrapper-bt1
{
  color: red;
}

【讨论】:

  • 它解决了我的问题,可惜我需要从父容器中包装它。这样做会很好,与自身组件隔离。
  • 是的,我想不出其他办法,除非你不使用渲染器并直接攻击 DOM(但通常不建议这样做)。该演示对我有用(它只是将newClass 类添加到按钮容器中,仅此而已)
  • 这样的实现应该封装在组件中。我看不到其他方式。您能否向我介绍有关该问题的信息?
【解决方案2】:

添加参考:

<div #myRef class="btn-wrapper-bt1">
   <button>AAA</button>
</div>

在你的 TS 中:

@ViewChild('myRef') myElement: ElementRef;

myFunc(){
    // do whatever you want with it AFTER you third party module finished its job (that's your call)
    //this.myElement.nativeElement.querySelector()
    //this.myElement.nativeElement.classList.remove('toto')
}

【讨论】:

  • 我无法将引用放在它在 node_modules 中的元素上
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-07
  • 1970-01-01
  • 1970-01-01
  • 2017-05-16
  • 2015-02-27
  • 2018-11-17
  • 2023-03-31
相关资源
最近更新 更多