如何从Angular2模板(的一部分)生成html?

时间:2019-02-25 17:57:24

标签: html angular

我需要允许我的最终用户将组件模板的html输出复制/粘贴到例如MailChimp模板或自己的网站(如静态html)。我需要类似于在某些内容管理网站上生成可嵌入iframe代码的按钮,以便用户可以将iframe html粘贴到自己网站的相应部分。

我的(简化的)组件模板,其部分如下所示:

<div *ngFor="let item of items">
  <p>{{item.title}}</p>
</div>

...在运行时应在DOM中创建如下所示的html:

<p>item title 1</p>
<p>item title 2</p>
<p>item title 3</p>
.
.

我想给我的用户一个按钮,它将生成的html复制到他们的剪贴板,以便他们可以粘贴和显示它,例如在自己的静态网站的相应部分中。我已经有一个自定义的copy-to-clipboard指令,它将处理传递给它的任何字符串的实际复制操作,但是在这种情况下,我应该复制什么?如何访问用户在浏览器中看到的HTML“ <p>item title 1</p>...”的“静态”版本?

请让我知道我的问题是否需要进一步说明。 Google的结果似乎表明这不是一个常见的操作,因此我很难用适当的术语来表达这个问题。

3 个答案:

答案 0 :(得分:0)

使用&lt;并且&gt;我在下面使用过。

<div *ngFor="let item of items">
  &lt;p&gt;{{item.title}}&lt;/p&gt;
</div>

答案 1 :(得分:0)

尝试在组件的变量中转换标题,如下所示:

items = [{title: "<p>item title 1</p>"}, {title: "<p>item title 2</p>"}, {title: "<p>item title 3</p>"}]

然后重做您的代码:

<div *ngFor="let item of items">
   {{item.title}}
</div>

答案 2 :(得分:0)

您可以使用组件中的自定义指令来实现它:

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

@Directive({
  selector: '[myInnerHtml]'
})
export class MyInnerHtmlDirective {
  constructor(private _el: ElementRef) {}
  getInnerHtml(): string {
    return this._el.nativeElement.innerHTML;
  }
}

使用内部组件模板:

<div (click)="click()" myInnerHtml>
  <p *ngFor="let item of items">{{item}}</p>
</div>

组件:

import { Component, ViewChildren } from '@angular/core';
import { MyInnerHtmlDirective } from '../my-first.directive';

@Component({
  selector: 'test',
  templateUrl: './test.component.html'
})
export class TestComponent {
  @ViewChildren(MyInnerHtmlDirective) directives;
  constructor() { }
  items: string[] = ['item title 1', 'item title 2', 'item title 3']

  click() {
    let html: string = (<MyInnerHtmlDirective>this.directives.first).getInnerHtml();
    let cleanHmtl: string = html.replace(/<!--[\s\S]*?-->/g, ''); // deleting comments
    console.log(cleanHmtl);
  }
}

它应该给您<p>item title 1</p><p>item title 2</p><p>item title 3</p>