2016-10-08 44 views
3

我想在.ts文件中有一个模板字符串并将其添加到NgTemplateOutlet。带字符串变量的Angular 2 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文件中的模板字符串,所以我如何实现这一点,使模板可以得到一个功能?

+0

你能为同提供plunker? – micronyks

+2

什么是$隐式的? –

+0

@GünterZöchbauerfrom [docs](https://angular.io/docs/ts/latest/api/common/index/NgTemplateOutlet-directive.html):注意:使用上下文对象中隐含的键$将它设置为值作为默认值。但是,它似乎没有在提供的代码中以任何有效的方式使用。 – altschuler

回答

3

更新角5

ngOutletContext更名为ngTemplateOutletContext

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

如果你想使用包含样结合Angular2特定语法的字符串,那么你需要在运行时创建一个组件t他的字符串被用作组件模板。另请参见Equivalent of $compile in Angular 2

$implicit可用于像

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

然后你就可以somecontextValue提供像

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

我看到:D没有问题。只需更新正确的问题。您可以删除与此q + a无关的评论。 –