Angular2:克隆组件/HTML 元素及其功能 [英] Angular2: Cloning component / HTML element and it's functionality

查看:22
本文介绍了Angular2:克隆组件/HTML 元素及其功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,问题很简单...

So, the question is fairly simple...

我有一个表格和一些角度逻辑(计算样式等)...特别是我在 THs 上有这个

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

显然角度逻辑不适用于 newTable,但我希望它是...

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

我该怎么做?

推荐答案

所以我做了一些研究,这就是我想出的.

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

您可以做到,而且使用模板和 [ngTemplateOutlet] 实际上并不难.这是它的工作原理:

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

因此,您创建了一个参考模板,将所有逻辑添加到其中,然后您只需使用 [ngTemplateOutlet] 创建模板的尽可能多的副本.保留了所有内部绑定和角度功能.

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.

这是一个工作的plunker:

Here is a working plunker:

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

如您所见,我已经使用 *ngIf[ngStyle] 对其进行了测试,它们按预期工作,我看不出任何其他原因指令不起作用.

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.

您甚至可以使用*ngFor,但是您需要提供[ngOutletContext].我已经在我正在处理的图书馆中完成了这项工作,您可以在此处查看示例:

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

这篇关于Angular2:克隆组件/HTML 元素及其功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆