[英]Angular Error The selector did not match any elements
在Angular 5组件中,出现错误: Error: The selector "#person-component" did not match any elements.
事实是,当我检查页面时,该元素在那里具有正确的ID。 另外,当我从路由器链接加载页面时,它可以工作,只有当我直接导航到URL时,我才会收到错误消息。
它找不到的元素是由另一个组件添加的,我正在将其添加到包含父组件的模块中。 显然,当我使用来自主要组件的链接时,正在发生一些不同的事情,但是我不知道那是什么。 失败的行(在下面)在ngAfterContentInit
,所以我不知道为什么它找不到元素。
这是组件中失败的代码:
ngAfterContentInit () {
...
const container = this.renderer.selectRootElement('#person-component');
this.renderer.setAttribute(container, 'id', htmlId);
...
}
这是添加方式。
主要组件HTML:
<employee-component> ... </employee-component>
子组件:
@Component({
...
selector: 'employee-component',
template: `
<div id="person-component"></div>
`,
})
这是检查页面时的元素:
<div id="person-component"></div>
使用ngAfterViewInit
而不是ngAfterContentInit
:
ngAfterViewInit () {
const container = this.r.selectRootElement('#person-component');
this.renderer.setAttribute(container, 'id', htmlId);
}
我们使用ngAfterContentInit
等待<ng-content>
预计内容被加载。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.