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

后端 未结 1 1965
陌清茗
陌清茗 2020-12-29 04:20

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.         


        
相关标签:
1条回答
  • 2020-12-29 05:24

    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

    0 讨论(0)
提交回复
热议问题