我想在.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文件中的模板字符串,所以我如何实现这一点,使模板可以得到一个功能?
你能为同提供plunker? – micronyks
什么是$隐式的? –
@GünterZöchbauerfrom [docs](https://angular.io/docs/ts/latest/api/common/index/NgTemplateOutlet-directive.html):注意:使用上下文对象中隐含的键$将它设置为值作为默认值。但是,它似乎没有在提供的代码中以任何有效的方式使用。 – altschuler