【问题标题】:Is it possible to parse the templateURL in an Angular component?是否可以在 Angular 组件中解析 templateURL?
【发布时间】:2020-05-31 21:44:00
【问题描述】:

我希望通过解析我的组件的 templateUrl 中已经存在的 HTML 来生成目录 (ToC)。

这是我的 component.ts :

@Component({
  selector: 'app-presentation',
  templateUrl: './presentation.component.html',
  styleUrls: ['./presentation.component.css']
})
export class PresentationComponent implements OnInit {
  public toc = '';

  constructor() { }

  ngOnInit(): void {
    // parse tempalteUrl here
    // set the this.toc variable
  }
}

这是我的 component.html :

<div class="container">
  <div class="row">
    <div class="col-sm-4">
      {{toc}}
    </div>
    <div class="col-sm-8">
      <h1>Title</h1>
      <h2>Sub Title1</h2>
      <p>some text</p>
      <h2>Sub Title2</h2>
      <p>more text</p>
      <h1>Title2</h1>
      <h2>Sub Title3</h2>
      <p>random text</p>
      <h2>Sub Title4</h2>
      <p>extra text</p>
    </div>
  </div>
</div>

我想做的是提取所有的 and 子节点,然后用它们来生成 ToC。

只有&lt;div class="col-sm-8"&gt; 有我感兴趣的元素
所有 &lt;h1&gt; 都是该 div 的直接子级
所有&lt;h2&gt; 都是&lt;h1&gt; 的直接子代

当我想更改网站内容时,我尝试做的目标是在每次更新时编辑尽可能少的 HTML。

【问题讨论】:

  • 你可以在构造函数中注入ElementRef,然后通过调用this.elRef.nativeElement.innerHTML来获取html。这对于阅读来说足够安全,但是如果你想操作它,Angular 建议使用 Renderer2
  • 我可能没有正确使用它:尝试这样做:constructor(private renderer: Renderer2, private el: ElementRef) { console.log(this.el.nativeElement.innerHTML); } 但我最终得到一个空字符串。直接记录 nativeElement 时我可以看到内容,但没有。我做错了什么?
  • 您需要在 ngOnInit 或更高版本中执行此操作,因为如果您在构造函数中执行此操作,则视图尚未初始化,这就是空字符串的原因

标签: html angular parsing templates


【解决方案1】:

如果只是阅读整个 HTML 文档,我能想到的几种方法是注入 ElementRef,如果要修改 HTML 并在 ngOnInit() 中输出,则注入 Renderer2;在 ngAfterViewInit() 中添加模板 ref 并读取 ViewChild

&lt;div #toc class="col-sm-8"&gt;...&lt;/div&gt;

import { Component , ElementRef, ViewChild } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  @ViewChild('toc') toc: ElementRef;

  constructor(private elRef: ElementRef) {}

  ngOnInit() {
    console.log(this.elRef.nativeElement.innerHTML);
  }

  //template ref + viewChild
  ngAfterViewInit() {
    console.log(this.toc.nativeElement.innerHTML);
  }
}

【讨论】:

    猜你喜欢
    • 2016-08-04
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    • 2016-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-07
    相关资源
    最近更新 更多