首页 > 解决方案 > 角度自动目录

问题描述

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

标签: jqueryangularjsangular

解决方案


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

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'));
  }
}

推荐阅读