Angular 2 dynamic html



我在角度 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 绑定到您的 td 中,那么您可以使用 innerHTML 属性

<td ...[innerHTML]="whateverValue"...>

我更喜欢为此使用管道。 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>

相关内容

  • 没有找到相关文章

最新更新