加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

具有字符串变量的Angular 2 NgTemplateOutlet.

发布时间:2020-12-17 07:35:44 所属栏目:安全 来源:网络整理
导读:我想在.ts文件中有一个模板字符串,并将其添加到NgTemplateOutlet. 我希望这会起作用,但事实并非如此. template [ngTemplateOutlet]="template" [ngOutletContext]="$implicit" 其中template是范围中的字符串变量.所以我实现了这个,但是这不起作用,因为我想要
我想在.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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读