具有字符串变量的Angular 2 NgTemplateOutlet.

我想在.ts文件中有一个模板字符串,并将其添加到NgTemplateOutlet.

我希望这会起作用,但事实并非如此.

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

其中template是范围中的字符串变量.所以我实现了这个,但是这不起作用,因为我想要它.

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>

结果如下:
我在视图中看到了按钮.
发送消息1的第一个按钮将1输出到控制台.但是,另一个按钮不打印任何消息.

我想在.ts文件中保留templatestring,那么我该如何实现这一点,以便模板可以获得函数的保持?

更新Angular 5

ngOutletContext已重命名为ngTemplateOutletContext

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

原版的

如果要使用包含Angular2特定语法(如绑定)的字符串,则需要在运行时创建一个组件,此字符串用作组件模板.另见Equivalent of $compile in Angular 2

$implicit可以像

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

然后你可以使somecontextValue可用

<template #report let-context>
  <div>{{context}}</div> <!-- outputs `somecontextValue` -->
</template>

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...