gpt4 book ai didi

带有字符串变量的 Angular 2 NgTemplateOutlet。

转载 作者:太空狗 更新时间:2023-10-29 17:52:35 27 4
gpt4 key购买 nike

我想在 .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>

结果是:我到达 View 中的按钮。发送消息 1 的第一个按钮将 1 打印到控制台。但是,另一个按钮不会打印出任何消息。

我想在 .ts 文件中保留 templatestring 那么我该如何实现它以便模板可以获取函数?

最佳答案

更新 Angular 5

ngOutletContext 已重命名为 ngTemplateOutletContext

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

原创

如果您想使用包含 Angular2 特定语法(如绑定(bind))的字符串,那么您需要在运行时创建一个组件,将此字符串用作组件模板。另见 Equivalent of $compile in Angular 2

$implicit 可以像这样使用

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

然后你可以让somecontextValue

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

关于带有字符串变量的 Angular 2 NgTemplateOutlet。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39929931/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com