繁体   English   中英

如何在 Angular 组件中呈现带有上下文的模板?

[英]How can I render template with context in an Angular component?

我在 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. 对于第二个节点。

问题解决了!

我遇到的问题是因为我要求在运行时翻译脚本中的警报消息,而我不想使用ngx-translate 幸运的是,在 angular 9 中,在@angular/localize的帮助下,这个问题得到了解决,并且很容易通过这种方式将文本翻译成脚本:

@Component({
  template: '{{ title }}'
})
export class HomeComponent {
  title = $localize`You have 10 users`;
}

要了解更多信息,请访问https://blog.ninja-squad.com/2019/12/10/angular-localize/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM