【发布时间】:2018-07-27 03:30:48
【问题描述】:
我想将组件的ng-content 的innerText 获取为一个简单的字符串,以便能够重用它。
我尝试过这样的事情:
@Component({
selector: 'my-comp',
template: `
<div class="text-container">
<span class="text" [title]="text">{{text}}</span>
</div>
<ng-template #text>
<ng-content></ng-content>
</ng-template>
`
})
export class MyComponent implements AfterViewInit {
@ViewChild('text') text: TemplateRef<string>;
ngAfterViewInit(): void {
console.log(this.text);
}
}
我是这样使用它的:
<my-com>
My simple string text
</my-com>
目标是将我的字符串My simple string text 放入变量text ...
想法?
【问题讨论】:
-
上面的例子中是否显示了该文本?您需要在某处标记模板以使内容变为真实(被添加到 DOM)。我怀疑这是否可行。我认为您应该需要一个包含
My simple string text的模板引用,并根据需要随时标记此模板。<ng-content>投影仅用于在特定位置显示现有内容,而不是用于传递。 -
不,没有显示文本,因为我在变量文本中只有 TemplateRef。这是我的观点,我怎样才能获取我的模板的 innerText 。如果我放置一个带有模板出口的 ng-container,它可以工作,但我还需要将我的文本放在 title 属性中
-
没有
innerText,只要没有<ng-content>,只要<ng-template>没有盖章,就没有<ng-content>。
标签: angular typescript transclusion