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

谁都会走 提交于 2019-11-30 06:09:50
Filip Lauc

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: `
    <template #temp>
        <h1 [ngStyle]="{background: 'green'}">Test</h1>
        <p *ngIf="bla">Im not visible</p>   
    </template>
    <template [ngTemplateOutlet]="temp"></template>
    <template [ngTemplateOutlet]="temp"></template>
    `
})

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!