angular - 是否可以将组件的内容(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>
解决方案
给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 上的工作代码示例,供您参考。
推荐阅读
- android-tv - 如何为我的 Android TV App 实施“Now Playing Card”?
- python - 如何在 Python 中保存从灰度转换为 RGB 的图像?
- java - 如何用 Spring Boot 安全功能替换基本身份验证?
- ansible - 在 Ansible 中设置包版本
- python - 如何使用 matplotlib 和 numpy 将此直方图转换为点图/点图?
- postgresql - 嵌套的 SELECT 和 NOT IN 如何在 knex 中工作
- html - 不支持 flex-wrap 的旧 webkit 浏览器
- image - 如何在图像后获得“休息”
- javascript - Javascript 最大值最小值平均值
- php - xampp 的问题