【发布时间】:2019-11-03 19:37:21
【问题描述】:
我在 Angular8 中使用 ng-template 进行复数翻译,以便从组件向用户显示通知,但在附加到 DOM 之前我无法获得模板的完整生成的内部 HTML,因为上下文尚未绑定。
为此,我如何渲染模板及其上下文并获取其内部 HTML?
我尝试使用ViewContainerRef 来渲染模板并将其附加到 DOM 中,它工作正常,但我不想将某些内容附加到 DOM 并稍后阅读。
模板:
<ng-template #activeDeactiveSuccessMessage let-card="card">
<span i18n="@@card.notification">Notification</span>
<span i18n>{card.lockStatus, select,
LOCKED {Card number ending with {{card.number}} has been deactivated.}
UNLOCKED {Card number ending with {{card.number}} has been activated.}
other {Card number status changed to {{card.lockStatus}} }}</span>
</ng-template>
组件代码:
@ViewChild('activeDeactiveSuccessMessage', { static: false }) private activeDeactiveSuccessMessage: TemplateRef<any>;
Bellow 是将渲染的模板附加到 DOM 的代码的一部分,并且工作正常:
let el = this._viewContainerRef.createEmbeddedView(this.activeDeactiveSuccessMessage, { card });
但是我不想附加到 DOM,想在附加之前在组件内获取渲染模板。 使用下面的代码获取文本,但对于需要上下文的第二个节点,返回注释!:
let el = this.activeDeactiveSuccessMessage.createEmbeddedView({ card });
console.log(el.rootNodes[0].innerHTML); // --> Notification
console.log(el.rootNodes[1].innerHTML); // --> <!----><!----><!----><!---->
我希望第二个节点的输出为 Card number ending with 6236 has been deactivated.。
【问题讨论】:
标签: javascript angular angular-i18n