Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing TemplateRef gives an empty comment node in Angular2

Building a custom sorting component in Angular2, but I'm having trouble accessing a template variable. I need to be able to access the ng-template so that I can "clone/stamp" then element to create drop zones, based on the template provided.

I've tried using @ViewChild("dropzone"), but it also returns an empty comment node.

Here's the Component

@Component({
    selector: "my-sortable",
    template: `
        <ng-content select="my-sortable-content"></ng-content>
    `
})
export class SortableComponent implements AfterViewInit {

    @Input() //@ContentChild("dropzone")
    dzTemplate: any;

    onAfterViewInit() {
        // Outputs an object but the 
        // nativeElement is an empty 
        // comment node
        console.log(this.dzTemplate); 
    }
}

And here's the HTML

<my-sortable [dzTemplate]="dropzone">
    <ng-template #dropzone>
        <p>Hey, I'm a drop zone!!</p>
    </ng-template>
    <my-sortable-content>
        <div *ngFor="...">
            ...
        </div>
    </my-sortable-content>
</my-sortable>

enter image description here

like image 649
Matt Avatar asked Oct 29 '22 03:10

Matt


1 Answers

Found the solution. Turns out that the ElementRef object has the method createEmbeddedView() which will return a EmbeddedViewRef. From there, I can access the DOM elements in the rootNodes property. These nodes are not attached to any element yet, so they're perfect for cloning/stamping.

like image 186
Matt Avatar answered Jan 02 '23 19:01

Matt