angular - 将纯文本传递给 Angular 组件,在 typescript 级别访问 ng-content 值
问题描述
我有一个简单的组件:
@Component({
selector: 'app-my-component',
template: ``,
})
export class MyComponent {
content: string;
}
Hello World
当我像这样使用我的组件时,我希望 content 属性是:
<app-my-component>Hello World</app-my-component>
我怎样才能让它发生?
解决方案
您需要使用 Content projection (ng-content) 来显示父组件给出的文本并注入 ElementRef 以获取 typescript 文件中的值。
我的组件.component.ts
import { AfterViewInit, Component, ElementRef } from '@angular/core';
@Component({
selector: 'my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.scss'],
})
export class MyComponentComponent implements AfterViewInit {
content: string;
constructor(private elt: ElementRef) {
}
ngAfterViewInit() {
this.content = this.elt.nativeElement.childNodes[0].nodeValue;
console.log("content:", this.content);
}
}
我的组件.component.html
<ng-content></ng-content>
父组件.component.html
<my-component>My text</my-component>
编辑:@Input
如果您将内容投影到ng-container
.
推荐阅读
- vba - 从使用 VBA 的项目中返回过期的非摘要任务列表
- c# - 如何将 Years Quarters (4) 添加到我的参数中?
- vba - MS Access VBA AppActivate“发送传真”和 SendKeys
- javascript - 仅当文本输入为 0 时才禁用按钮
- javascript - 带有可拖动手柄的垂直拆分面板以调整面板的高度
- python - 你如何找到一个似乎没有在任何地方定义的 python 模块?
- wordpress - 单击wpml中的链接时如何保持当前语言
- android - Android - JSON 抛出异常
- google-bigquery - 在 Big Query 中使用通配符进行分组
- selenium - 无论我使用什么定位器,我都无法使用 Selenium 单击此按钮