例如我有:
<div class="btn-wrapper-bt1">
<button>AAA</button>
</div>
此按钮位于 node_modules/somebt
中存在的第 3 方元素上
我想在 Angular 环境中做一些简单的类更改。
在ngOnInit
中有没有简单的方法来改变它? ?或者我需要 fork 源代码并在源代码中更改它?
提前致谢。
最佳答案
在 html 中,添加对包含您的第 3 方组件的元素的 #ref
引用
yourComponent.html
<div #ref >
<your-3rd-party-component></your-3rd-party-component>
</div>
然后,在您的组件中,检索包含元素的子元素
你的组件.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
注意:如果你只是想改变第 3 方组件的外观,你可以在你自己的组件中覆盖类
你的组件.scss
:host ::ng-deep .btn-wrapper-bt1
{
color: red;
}
关于javascript - Angular 5 中的 DOM 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51187593/