krojew krojew - 1 year ago 210
AngularJS Question

Angular2 - getting a TemplateRef inside a service

Is there a way to get a TemplateRef for an existing html template inside a service?

Context of the question (since I may be doing something wrong in the first place):

I'm creating a service which uses NgbModal to display some text in a popup. The modal requires a TemplateRef to display the contents, which I don't exactly know how to create. The other options are to pass a string (which is escaped, and I need to display html) or to pass a component (which I don't know how to pass the desired text to).

Answer Source

Two ways

  • <template> from the components template:
  • <template> passed as child from the outside

(not tested)

  selector: 'foo',
  template: '<template #ref1>xxx</template>'
class MyComponent {
  @ViewChild('ref1') template1:TemplateRef;

  constructor(private template2:TemplateRef, private someService:SomeService) {
    someService.template2 = template2;

  ngAfterViewInit() {
    this.someService.template1 = this.template1;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download