0

我在 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> 
4

2 回答 2

0

如果您只是想将 html 绑定到您的 td 听起来,那么您可以使用 innerHTML 属性

<td ...[innerHTML]="whateverValue"...>
于 2017-06-23T06:13:20.333 回答
0

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

于 2017-09-05T18:19:25.737 回答