[英]DOM Manipulations in Angular 5
例如,我有:
<div class="btn-wrapper-bt1"> <button>AAA</button> </div>
此按鈕位於node_modules/somebt
中存在的第3方元素上
我想在Angular環境中進行一些簡單的類更改。
有沒有一種簡單的方法可以在ngOnInit
進行更改? 還是我需要派生源並在源中進行更改?
提前致謝。
在html中,添加對包含第3方組件的元素的#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;
}
添加參考:
<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')
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.