该错误通常发生在使用Angular Universal或Ionic时。解决此问题的方法是确保在ngOninit生命周期钩子函数中使用了一些公共功能,例如head.querySelector是有效的DOM节点,否则会抛出此错误。 在以下示例中,可以看到如何在exampleComponent组件中使用ngOnInit生命周期钩子函数正确地调用querySelector:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-example',
template: `Hello World`
})
export class ExampleComponent implements OnInit {
ngOnInit() {
const head = document.getElementsByTagName('head')[0];
const style = document.createElement('style');
style.innerHTML = 'h1 { color: red; }';
head.appendChild(style);
}
}