Search code examples
javascriptangularangular2-directives

Angular2: Cloning component / HTML element and it's functionality


So, the question is fairly simple...

I have a table and some angular logic on it (calculating styles, etc)... specifically I have this on THs

[class.hidden] = "column.group !== 'key-data' && currentTableView !== column.group"

For my table sticky headers functionality I need to clone the table and position it fixed.. using a directive, that does something like this (simplified)

let newTable = element.cloneNode(true);
body.appendChild(newTable);

obviously the angular logic is not applied to the newTable, but I want it to be...

How do I do it?


Solution

  • So I did some research and this is what I came up with.

    You can do it and it isn't actually that hard using templates and the [ngTemplateOutlet]. This is how it works:

    @Component({
      selector: 'my-app',
      template: `
        <ng-template #temp>
            <h1 [ngStyle]="{background: 'green'}">Test</h1>
            <p *ngIf="bla">Im not visible</p>   
        </ng-template>
        <ng-container *ngTemplateOutlet="temp"></ng-container>
        <ng-container *ngTemplateOutlet="temp"></ng-container>
        `
    })
    
    export class AppComponent {
        bla: boolean = false;
        @ContentChild('temp') testEl: any;
    } 
    

    So you create a reference template, add all of your logic inside of it, and then you just create as many copies of the template using the [ngTemplateOutlet]. All of the inner bindings and angular functionality is retained.

    Here is a working plunker:

    http://plnkr.co/edit/jPt5eKUfLUe9FxnLH8bL?p=preview

    As you can see I've tested it with *ngIf and [ngStyle] and they work as expected and I don't see any reason why any other kind of directive wouldn't work.

    You can even use *ngFor but then you need to provide the [ngOutletContext]. I've done that in a library I'm working on you can see an example here:

    https://github.com/flauc/ng2-simple-components/blob/master/src/select/select.component.ts