微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

具有字符串变量的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>

原文地址:https://www.jb51.cc/angularjs/142494.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐