带字符串变量的Angular 2 NgTemplateOutlet. [英] Angular 2 NgTemplateOutlet with string variable.

查看:68
本文介绍了带字符串变量的Angular 2 NgTemplateOutlet.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to have a string of a template in the .ts-file and add it to the NgTemplateOutlet.

我希望这能奏效,但没有奏效.

I was hoping this would work but it did not.

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

其中template是作用域中的字符串变量.因此,我实现了这一点,但是由于我想要的话,这还是行不通的.

where template is a string-variable in the scope. So I implemented this, however this does not work as I wanted it to either.

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输出到控制台.但是,其他按钮不会打印出任何消息.

Which results in this: I get to buttons in the view. The first button which sends the message 1, prints out 1 to the console. The other button does however not print out any message.

我想保留.ts文件中的templatestring,那么如何实现此目的,以便模板可以保留这些函数?

I would like to keep to templatestring in the .ts file so how do i implement this so that the template can get a hold of the functions?

推荐答案

更新Angular 5

ngOutletContext重命名为ngTemplateOutletContext

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

原始

如果要使用包含诸如绑定之类的Angular2特定语法的字符串,则需要在运行时创建一个组件,该字符串用作组件模板.另请参见在Angular 2中等效于$ comp

If you want to use a string that contains Angular2 specific syntax like binding, then you need to create a component at runtime where this string is used as components template. See also Equivalent of $compile in Angular 2

$implicit可以像

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

然后您可以像

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

这篇关于带字符串变量的Angular 2 NgTemplateOutlet.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆