简体   繁体   中英

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

I'm using ng-template in Angular8 to make a plural translation for displaying a notification to the user from the component but I cannot get full generated inner HTML of the template before attaching to DOM because context not bound yet. How can I render a template with its context and get its inner HTML for this purpose?

I tried to use ViewContainerRef to render the template and attach it DOM and it works fine but I don't want to attach something to DOM and read it later.

Template:

<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>

Component Code:

@ViewChild('activeDeactiveSuccessMessage', { static: false }) private activeDeactiveSuccessMessage: TemplateRef<any>;

Bellow is part of code to attach the rendered template to DOM and works fine:

let el = this._viewContainerRef.createEmbeddedView(this.activeDeactiveSuccessMessage, { card });

But I don't want to attach to DOM , want to get rendered template inside component before attaching . used bellow code to get text but for second node which needed context, returns comment::

let el = this.activeDeactiveSuccessMessage.createEmbeddedView({ card });
console.log(el.rootNodes[0].innerHTML); // -->     Notification
console.log(el.rootNodes[1].innerHTML); // -->     <!----><!----><!----><!---->

I expect the output of Card number ending with 6236 has been deactivated. for the second node.

Problem SOLVED!

The problem I encountered was because of my request to translate alert messages in the script at runtime, and I did not want to use ngx-translate . Fortunately, in angular 9, with the help of @angular/localize , this problem has been solved and it is easy to translate texts into the script in this way:

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

to read more visit https://blog.ninja-squad.com/2019/12/10/angular-localize/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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