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

查看:83
本文介绍了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: `
    <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;
} 

因此,您创建一个参考模板,在其中添加所有逻辑,然后你只需使用 [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.

以下是一名工作人员:

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天全站免登陆