在Angular中,Element.createShadowRoot()
方法已被废弃,可以使用Element.attachShadow()
方法替代。以下是一个示例代码:
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
@Component({
selector: 'app-shadow-root',
template: `
Hello Shadow DOM
`
})
export class ShadowRootComponent implements OnInit {
@ViewChild('rootElement', { static: true }) rootElement: ElementRef;
ngOnInit() {
const element = this.rootElement.nativeElement;
if (element.attachShadow) {
const shadowRoot = element.attachShadow({ mode: 'open' });
shadowRoot.innerHTML = `
Hello from Shadow DOM
`;
} else {
console.warn('Shadow DOM is not supported');
}
}
}
在上述示例代码中,我们使用@ViewChild
装饰器来获取模板中的元素,并使用
ElementRef
来访问原生DOM元素。然后,我们使用element.attachShadow()
方法创建一个Shadow DOM,并使用shadowRoot.innerHTML
来定义Shadow DOM的内容。