角度自动目录

Posted

技术标签:

【中文标题】角度自动目录【英文标题】:Angular auto table of contents 【发布时间】:2020-07-28 19:01:43 【问题描述】:

我正在尝试以角度制作自动目录。为此,我需要通过标签获取元素(h1,h2..etc)。有谁知道 Angular 中 jquery document.getelementbytagname ('h1, h2, h3') 的等效功能? ViewChildren 不起作用,因为它无法按标签查找项目。 ViewChildren 与#id 和组件一起使用。我需要帮助!提前感谢

【问题讨论】:

【参考方案1】:

如果我理解正确,那么这将解决你的问题

import  Component, Input, ElementRef, Inject, OnInit from '@angular/core';
import  DOCUMENT  from '@angular/common'; 

@Component(
  selector: 'hello',
  template: `<h1>Hello name!</h1><h1>Hello name!</h1><h1>Hello name!</h1>`,
  styles: [`h1  font-family: Lato; `]
)
export class HelloComponent implements OnInit 
  @Input() name: string;

  constructor(@Inject(DOCUMENT) private document: htmlElement)

  

  ngOnInit() 
    console.log(this.document.getElementsByTagName('h1'));
  

【讨论】:

这样做你会使用jquery吗? 不,只有角度。您可以在stackblitz.com/edit/angular-getelementbytag 中查看示例

以上是关于角度自动目录的主要内容,如果未能解决你的问题,请参考以下文章