【问题标题】:Angular 2 NgTemplateOutlet with string variable.带有字符串变量的 Angular 2 NgTemplateOutlet。
【发布时间】: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 会将其值设置为默认值。但是,在提供的代码中似乎没有以任何有效的方式使用它。
  • 应该是&lt;template [ngTemplateOutlet]="template" [ngOutletContext]="{$implicit: 'somecontextValue}"&gt;

标签: angular


【解决方案1】:

更新 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>

【讨论】:

  • 我明白了:D 没有问题。只需更新正确的问题。可以删除与本q+a无关的cmet。
  • 我认为可能缺少单引号,或者不小心添加了一个。
猜你喜欢
  • 2018-10-03
  • 1970-01-01
  • 1970-01-01
  • 2019-01-28
  • 1970-01-01
  • 2020-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多