【问题标题】:Create table of contents from headings从标题创建目录
【发布时间】:2018-12-09 20:03:43
【问题描述】:

在 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 的实现方式是什么?

【问题讨论】:

    标签: angular tableofcontents


    【解决方案1】:

    您可以使用以下方法将类添加到您的 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 以在页面中列出它们:

    应用组件.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>
    

    应用组件.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.

    【讨论】:

    • 感谢您的建议,但我希望它使用问题中所述的相应组件样式文件中定义的样式。
    • 谢谢,虽然ul#page-toc { ::ng-deep li { color: red; } } 会完成这项工作,但我正在寻找如何将我上面的 javascript 示例更改为不需要我使用这些技巧的方法。
    • 如果您要动态添加文章和标题并且用户创建它们,以便您可以在添加新标题时动态添加 page-toc 元素。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    • 1970-01-01
    • 2016-01-14
    • 2012-08-06
    • 1970-01-01
    相关资源
    最近更新 更多