如何从Angular中绑定的innerHTML访问子级?

时间:2018-10-28 18:37:52

标签: angular

HTML如下:

<div [innerHtml]="someHtml"></div>

someHtml看起来像这样:

public someHtml = '<code>test</code><code>another test</code>';

我正在尝试使用ContentChildren获取代码块,但是返回的长度为0。

@ContentChildren('code') public codeBlocks;

public ngAfterContentInit(): void {
    console.log(this.codeBlocks); // returns length of 0
}

如何获取通过innerHtml绑定到div的代码块的引用? HTML实际上是从后端API中提取的,我的目标是向每个块添加一个“复制”按钮。

3 个答案:

答案 0 :(得分:2)

如果您可以有多个with recursive cte(id, active_date) as ( select id, activated_date as active_date from your_table union all select t.id, active_date + justify_days(interval '1 days') from cte inner join your_table t on cte.id = t.id where cte.active_date < now() ) select * from cte order by 1, 2; 元素,则应使用code,对于单个@ViewChildren元素,可以使用code

答案 1 :(得分:1)

ngAfterContentInit适用于使用ng-content / ng-slot的内容投影。使用ngAfterViewInit应该可以。另外,将查询更改为使用ViewChild来查询呈现的html。

@ViewChild('code') public codeBlocks;

答案 2 :(得分:0)

我能够通过以下代码解决此问题:

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

@Component({
  selector: 'app-main',
  templateUrl: './main.component.html',
  styleUrls: ['./main.component.scss']
})
export class MainComponent implements OnInit, AfterViewInit {
  @ViewChild('codeWrap') public codeWrap: ElementRef;

  public someCode = '<code>hi</code><p>blah</p><code>test</code><p>blah</p><code>test</code>';

  constructor(
    private renderer: Renderer2
  ) { }

  ngOnInit() {
  }

  public ngAfterViewInit(): void {
    const codeBlocks: HTMLCollection = this.codeWrap.nativeElement.getElementsByTagName('code');

    Array.from(codeBlocks)
      .forEach((codeBlock): void => {
        const button = this.renderer.createElement('button');
        const text = this.renderer.createText('copy');
        const wrap = this.renderer.createElement('div');
        const parent = codeBlock.parentNode;

        // set wrap position to relative
        this.renderer.setStyle(wrap, 'position', 'relative');

        // set button styles
        this.renderer.appendChild(button, text);
        this.renderer.setStyle(button, 'position', 'absolute');
        this.renderer.setStyle(button, 'top', '0');
        this.renderer.setStyle(button, 'right', '0');

        // listen for button click event
        this.renderer.listen(button, 'click', (ev) => {
          const codeToCopy = codeBlock.innerHTML;

          console.log(codeToCopy);
        });

        // insert elements
        this.renderer.insertBefore(parent, wrap, codeBlock);
        this.renderer.appendChild(wrap, button);
      });
  }
}