In Angular2, I need to duplicate a node rather than moving it in some cases. That node has angular2 properties so cloneNode doesn\'t work. How can I do it?
*what doe
Let's use the following markup for illustration:
Paragraph One
Paragraph Two
Paragraph Three
Option 1 - Manually wrap the element to clone inside a tag
This is basically what you did, only instead of printing out the template with ngTemplateOutlet, grab a reference to it in your component's class and insert it imperatively with createEmbeddedView().
@Component({
selector: 'my-app',
template: `
Paragraph One
Paragraph Two
Paragraph Three
`
})
export class AppComponent{
// What to clone
@ViewChild('clone') template;
// Where to insert the cloned content
@ViewChild('container', {read:ViewContainerRef}) container;
constructor(private resolver:ComponentFactoryResolver){}
cloneTemplate(){
this.container.createEmbeddedView(this.template);
}
}
In this example, I'm inserting the "clone" at a specific location in the markup (), but you could also append it at the bottom of the current component's template.
Also note that the original Paragraph Two is no longer visible.
Option 2 - Use a structural directive
If you want to clone an element at its current location, ending up with:
Paragraph One
Paragraph Two
Paragraph Two
Paragraph Three
Then you could create a structural directive *clone and apply it to the paragraph to clone, like this:
Paragraph One
Paragraph Two
Paragraph Three
Interestingly, what a structural directive does is wrap the element it is applied to inside a tag. Pretty similar to what we did in option 1, only in that case we have NO CONTROL over the location where the clones are printed out (they will appear where the original paragraph was).
This would essentially replicate *ngFor's behavior so it's probably not very useful. Also, it seems from your comment to yurzui that it's not what you want.