首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角5中的DOM操作

角5中的DOM操作
EN

Stack Overflow用户
提问于 2018-07-05 09:16:53
回答 2查看 1.9K关注 0票数 1

例如,我有:

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

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

我想在角度环境中做一些简单的类改变。

ngOnInit中有简单的方法来改变它吗?或者我需要分叉源并在源中更改它?

提前谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-07-05 11:22:25

在html中,向包含第三方组件的元素添加一个#ref引用。

yourComponent.html

代码语言:javascript
复制
<div #ref >
   <your-3rd-party-component></your-3rd-party-component>
</div>

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

yourComponent.ts

代码语言:javascript
复制
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演示

注意事项:如果您只想更改第三方组件的外观,可以在自己的组件中重写类

yourComponent.scss

代码语言:javascript
复制
:host ::ng-deep .btn-wrapper-bt1
{
  color: red;
}
票数 2
EN

Stack Overflow用户

发布于 2018-07-05 10:01:20

添加一个参考资料:

代码语言:javascript
复制
<div #myRef class="btn-wrapper-bt1">
   <button>AAA</button>
</div>

在你的TS中:

代码语言:javascript
复制
@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')
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51187593

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档