从标题创建目录

时间:2018-12-09 10:53:09

标签: angular tableofcontents

在Angular中,如何从页面上的标题元素创建目录?

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 个答案:

答案 0 :(得分:0)

您可以使用以下方法将课程添加到您的li:

li.className = "test"

并在src文件夹的全局styles.css中设置样式以测试类,例如在styles.css中进行测试:

.test{
  color: red;
}

DEMO

或者您可以在组件css中用:host / deep /前缀css:

:host /deep/ .test{
  color: red;
}

DEMO

或将封装设置为ViewEncapsulation.None并使用组件css:

import { ViewEncapsulation } from '@angular/core';

@Component({
    ...
    encapsulation: ViewEncapsulation.None
})

更新

您可以在html中定义tocPage子级,然后将标题发送到tocPage以在页面中列出它们:

app-component.html:

<article id="page">    
    <page-toc [elements]="titles"></page-toc>
    <h2>Foo</h2>
    <p>lorem ipsum...</p>

    <h2>Bar</h2>
    <p>lorem ipsum...</p>
</article>

app-component.ts:

export class AppComponent  {

  public titles: string[] = []
  constructor(){}

  ngOnInit(){
      this.createToc();
  }
  createToc() {
    let elemArticle = document.getElementById("page");
    var myArrayOfNodes = [].slice.call( elemArticle.querySelectorAll("h2") );
    console.log(myArrayOfNodes)
    myArrayOfNodes.forEach((value, key) => {
      this.titles.push(value.innerHTML)
    })
  }
}

page-toc.component.ts

export class PageToc  {
  @Input() elements: string[];
}

page-toc.component.html

<ul id="page-toc">
  <li class="title" *ngFor="let element of elements">
    {{element}}
  </li>
</ul>

page-toc.component.css:

.title{
  color: red;
}

DEMO