首页 文章

从 Headers 创建目录

提问于
浏览
0

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 回答

  • 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
    })
    

    update

    你可以在你的html中定义一个tocPage子项,并将 Headers 发送到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)
        })
      }
    }
    

    页面toc.component.ts

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

    页面toc.component.html

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

    页面toc.component.css:

    .title{
      color: red;
    }
    

    DEMO .

相关问题