Angular 2 动态 html
Posted
技术标签:
【中文标题】Angular 2 动态 html【英文标题】:Angular 2 dynamic html 【发布时间】:2017-11-26 14:33:48 【问题描述】:我在 Angular 2 视图中创建了一个表格,我想动态绑定 html 或 Angular 组件。
<tbody>
<tr *ngFor="let hHeader of hHeaders;let x=index">
<td class="hour"><span>hHeader</span></td>
<td *ngFor="let vHeader of vHeaders;let y=index" class="hour " [contextMenu]="basicMenu " [contextMenuSubject]="t:hHeader,d:vHeader,x:x,y:y ">
<div #values [class.cell]="cell" id="cell-x-y" style="width:100%; height: 100%"></div>
</td>
</tr>
</tbody>
我可以识别组件中的每个单元格
for (let i = 0; i < cells.length; ++i)
if (cells[i].nativeElement.id == 'cell-' + event.x + '-' + event.y)
// cells[i].nativeElement.style.backgroundColor = '#5789D8';
cells[i].nativeElement.innerHTML = '<div class="drag" dnd-draggable [dragEnabled]="true">Drag me</div>'
console.log(cells[i]);
但我不能像这样绑定 html 或组件。
<div class="drag" dnd-draggable [dragEnabled]="true">Drag me</div>
【问题讨论】:
您到底在寻找什么? 我想将html或angular 2组件添加到如果您只是想将 html 绑定到您的 td,就像听起来一样,那么您可以使用 innerHTML 属性
<td ...[innerHTML]="whateverValue"...>
【讨论】:
我认为nativeElement.innerHTML = '<div class="drag" dnd-draggable [dragEnabled]="true">Drag me</div>'
这个不是通过编译器编译的。它需要作为字符串。我使用了一些 npm 包。他们不工作【参考方案2】:
我更喜欢为此使用管道。 https://angular.io/guide/security#bypass-security-apis
我在论坛https://forum.ionicframework.com/t/inserting-html-via-angular-2-use-of-domsanitizationservice-bypasssecuritytrusthtml/62562/2找到了这个
import Pipe, PipeTransform from '@angular/core';
import DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl from '@angular/platform-browser';
@Pipe(
name: 'safe'
)
export class SafePipe implements PipeTransform
constructor(protected _sanitizer: DomSanitizer)
public transform(value: string, type: string = 'html'): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl
switch (type)
case 'html': return this._sanitizer.bypassSecurityTrustHtml(value);
case 'style': return this._sanitizer.bypassSecurityTrustStyle(value);
case 'script': return this._sanitizer.bypassSecurityTrustScript(value);
case 'url': return this._sanitizer.bypassSecurityTrustUrl(value);
case 'resourceUrl': return this._sanitizer.bypassSecurityTrustResourceUrl(value);
default: throw new Error(`Invalid safe type specified: $type`);
要实现只需使用<component-container [innerHtml]='this.safteyPipe.transform(TemplateComponentString)'></component-container>
【讨论】:
以上是关于Angular 2 动态 html的主要内容,如果未能解决你的问题,请参考以下文章