In Angular, how can I create a table of contents from the heading elements on the page?
HTML:
<article id="page">
<ul id="page-toc">
<!-- auto-generated toc-items go here -->
</ul>
<h2>Foo</h2>
<p>lorem ipsum...</p>
<h2>Bar</h2>
<p>lorem ipsum...</p>
</article>
TS:
export class MyComponent implements OnInit {
createToc() {
let elemArticle = document.getElementById("page");
var myArrayOfNodes = [].slice.call( elemArticle.querySelectorAll("h2") );
var toc = document.getElementById("page-toc");
myArrayOfNodes.forEach( function(value, key, listObj) {
var li = toc.appendChild(document.createElement("li"));
li.innerHTML = value.innerHTML;
})
ngOnInit() {
this.createToc();
}
}
这样运行没有错误,li元素确实出现在页面上 . 但是,my-component.scss中定义的css不会应用于它们 . 这让我相信Angular并不真正了解自动生成的li元素 .
实现这一目标的Angular方法是什么?
1 回答
您可以使用以下方法为您的li添加课程:
并将样式设置为src文件夹的全局styles.css中的测试类,例如在styles.css中:
DEMO
或者你可以在你的组件css中使用:host / deep /前缀你的css:
DEMO
或将封装设置为
ViewEncapsulation.None
并使用组件css:update :
你可以在你的html中定义一个tocPage子项,并将 Headers 发送到tocPage以在页面中列出它们:
APP-component.html:
APP-component.ts:
页面toc.component.ts
页面toc.component.html
页面toc.component.css:
DEMO .