是否有可能以字符串形式获取组件的内容(ng-content)?

时间:2019-12-10 11:58:27

标签: angular typescript

我们正在构建一个设计系统,对于我们的文档,我们希望在呈现的组件旁边显示代码。

<br-code-example>
  <br-button type="primary">
    Primary default
  </br-button>
</br-code-example>

是否有可能以字符串形式获取ng-content中的内容(以及将其保留在ng-content中以使其呈现)?

<br-button type="primary">
  Primary default
</br-button>

2 个答案:

答案 0 :(得分:2)

将模板变量提供给ng-content标签。然后使用ContentChild在组件中访问它。

尝试一下:

import { Component, Input, ContentChild } from '@angular/core';

@Component({
  selector: 'hello',
  template: `
    <h1>Hello {{name}}!</h1>
    <ng-content #projected></ng-content>
  `,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
  @Input() name: string;
  @ContentChild('projected', { static: false }) projectedContent;

  ngAfterContentInit() {
    console.log('child: ', this.projectedContent.nativeElement.innerHTML);
  }
}

  

这是您推荐的Working Code Example on StackBlitz

答案 1 :(得分:0)

因此我们设法通过节点脚本生成页面的component.html来获得所需的结果。

  • br-code-example组件具有一个输入code,该输入包含带有代码的字符串。
  • 页面以markdown编写(如问题所述,带有<br-code-example> html片段。
  • 每次降价文件发生以下更改时,节点脚本都会运行:
    • 浏览每个markdown文件并搜索<br-code-example>标签
    • 获取这些标签之间的内容,并将其作为code道具添加到br-code-example
    • 将降价转换为html
    • 将html保存为[page].component.html