带有字符串变量的 Angular 2 NgTemplateOutlet。

Emm*_*son 4 angular

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

我希望这会奏效,但没有。

<template [ngTemplateOutlet]="template" [ngOutletContext]="$implicit">
Run Code Online (Sandbox Code Playgroud)

其中模板是范围内的字符串变量。所以我实现了这个,但是这也不能像我想要的那样工作。

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() {

  }

}
Run Code Online (Sandbox Code Playgroud)

HTML:

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

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

结果是:我进入了视图中的按钮。发送消息 1 的第一个按钮将 1 打印到控制台。然而,另一个按钮不会打印出任何消息。

我想在 .ts 文件中保留模板字符串,那么我如何实现它以便模板可以获取函数?

Gün*_*uer 5

更新角度 5

ngOutletContext 被重命名为 ngTemplateOutletContext

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

原来的

如果要使用包含 Angular2 特定语法(如绑定)的字符串,则需要在运行时创建一个组件,该字符串用作组件模板。另请参阅Angular 2 中 $compile 的等效项

$implicit 可以像

<template [ngTemplateOutlet]="template" [ngOutletContext]="{$implicit: 'somecontextValue'}">
Run Code Online (Sandbox Code Playgroud)

然后你可以somecontextValue

<template #report let-context>
  <div>{{context}}</div> <!-- outputs `somecontextValue` -->
</template>
Run Code Online (Sandbox Code Playgroud)