解决方法
您可以从任何组件执行此操作.例如:
- export class AppComponent implements AfterViewInit {
- constructor(private elementRef: ElementRef){
- }
- ngAfterViewInit(){
- this.elementRef.nativeElement.ownerDocument.body.style.backgroundColor = 'yourColor';
- }
- }
通过使用this.elementRef.nativeElement.ownerDocument,您可以访问window.document对象而不违反任何角度约定.当然,您可以使用window.document直接访问文档对象,但我认为最好通过ElementRef访问它.