4

I would like to have a string of a template in the .ts-file and add it to the NgTemplateOutlet.

I was hoping this would work but it did not.

<template [ngTemplateOutlet]="template" [ngOutletContext]="$implicit">

where template is a string-variable in the scope. So I implemented this, however this does not work as I wanted it to either.

import { Component, AfterViewInit } from '@angular/core';
import { ToastController } from 'ionic-angular';
import { ModalController } from 'ionic-angular';
import { DomSanitizer, SafeHtml} from '@angular/platform-browser';

@Component({
 selector: 'dynamic-report',
 templateUrl: 'dynamicReport.html',
})
export class DynamicReport implements AfterViewInit{
 private _template: string;
 context: any;

 public get template() : SafeHtml {
   return this.sanitizer.bypassSecurityTrustHtml(this._template);
 }

 constructor(public toastCtrl: ToastController, public modalCtrl:ModalController, private sanitizer: DomSanitizer) {
   this._template = "<button (click)='testFunction1('2')'>Click here 2!</button>";
   this.context = this;

 }

  testFunction1(message){
    console.log(message);
  }

  ngAfterViewInit() {

  }

}

HTML:

<template [ngTemplateOutlet]="report" [ngOutletContext]="$implicit">

</template>
<template #report>
  <button (click)='testFunction1("1")'>Click here 1!</button>
  <div [innerHtml]="template"></div>
</template>

Which results in this: I get to buttons in the view. The first button which sends the message 1, prints out 1 to the console. The other button does however not print out any message.

I would like to keep to templatestring in the .ts file so how do i implement this so that the template can get a hold of the functions?

Emma Vihlsson
  • 161
  • 2
  • 12

1 Answers1

5

update Angular 5

ngOutletContext was renamed to ngTemplateOutletContext

See also https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29

original

If you want to use a string that contains Angular2 specific syntax like binding, then you need to create a component at runtime where this string is used as components template. See also Equivalent of $compile in Angular 2

$implicit can be used like

<template [ngTemplateOutlet]="template" [ngOutletContext]="{$implicit: 'somecontextValue'}">

Then you can make somecontextValue available like

<template #report let-context>
  <div>{{context}}</div> <!-- outputs `somecontextValue` -->
</template>
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567