【发布时间】:2017-02-17 04:50:56
【问题描述】:
我想在 .ts 文件中有一个模板字符串并将其添加到 NgTemplateOutlet。
我希望这会奏效,但它没有。
<template [ngTemplateOutlet]="template" [ngOutletContext]="$implicit">
其中模板是范围内的字符串变量。所以我实现了这个,但是这也不能像我想要的那样工作。
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 吗?
-
什么是
$implicit? -
@GünterZöchbauer 来自docs:注意:在上下文对象中使用键 $implicit 会将其值设置为默认值。但是,在提供的代码中似乎没有以任何有效的方式使用它。
-
应该是
<template [ngTemplateOutlet]="template" [ngOutletContext]="{$implicit: 'somecontextValue}">
标签: angular