首页 > 解决方案 > 是否可以将组件的内容(ng-content)作为字符串获取?

问题描述

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

<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>

标签: angulartypescript

解决方案


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

这是StackBlitz 上的工作代码示例,供您参考。


推荐阅读