【问题标题】:How can I render template with context in an Angular component?如何在 Angular 组件中呈现带有上下文的模板?
【发布时间】: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


    【解决方案1】:

    问题解决了!

    我遇到的问题是因为我要求在运行时翻译脚本中的警报消息,我不想使用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/

    【讨论】:

      猜你喜欢
      • 2017-06-10
      • 2019-01-06
      • 1970-01-01
      • 2019-08-11
      • 2021-07-11
      • 2017-11-19
      • 2017-05-10
      • 2012-01-29
      • 1970-01-01
      相关资源
      最近更新 更多