例如,我有:
<div class="btn-wrapper-bt1"> <button>AAA</button> </div>
此按钮位于node_modules/somebt中存在的第三方元素上。
我想在角度环境中做一些简单的类改变。
在ngOnInit中有简单的方法来改变它吗?或者我需要分叉源并在源中更改它?
提前谢谢。
发布于 2018-07-05 11:22:25
在html中,向包含第三方组件的元素添加一个#ref引用。
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演示
注意事项:如果您只想更改第三方组件的外观,可以在自己的组件中重写类
yourComponent.scss
:host ::ng-deep .btn-wrapper-bt1
{
color: red;
}发布于 2018-07-05 10:01:20
添加一个参考资料:
<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')
}https://stackoverflow.com/questions/51187593
复制相似问题