0

I have created a table in angular 2 view and i want to bind html or angular component dynamically.

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

I can identify each cell in component

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]);
      }
    }

but i can't bind html or Component like this.

<div class="drag" dnd-draggable [dragEnabled]="true">Drag me</div> 
mayur
  • 3,558
  • 23
  • 37
Ishaka
  • 13
  • 8

2 Answers2

0

If you're just looking to bind html to your td like it sounds, then you can just use the innerHTML attribute

<td ...[innerHTML]="whateverValue"...>
Nieminen
  • 1,284
  • 2
  • 13
  • 31
  • i think `nativeElement.innerHTML = '
    Drag me
    '` this one is not compile through compilor. it takes as string. i used some npm packages. they are not working
    – Ishaka Jun 23 '17 at 06:16
0

I prefer using pipes for this. https://angular.io/guide/security#bypass-security-apis

I found this one in a forum 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}`);
        }
    }

}

To implement just use <component-container [innerHtml]='this.safteyPipe.transform(TemplateComponentString)'></component-container>

Rex
  • 376
  • 2
  • 11