yazz
yazz

Reputation: 301

How to create dynamic DOM element in angular?

I'm stuck at how to create a dom element in angular and pass it to jsPlumb which I am using to draw charts.

I create connections between nodes using jsPlumb and need to create an overlay on these connections. The offical jsPlumb documentation asks me to do something like this -

["Custom", {
    create:function(component) {
        return $("<select id='myDropDown'><option value='foo'>foo</option><option value='bar'>bar</option></select>");               
    },
    location:0.5,
    id:"customOverlay"
}]

In this line -

return $("<select id='myDropDown'><option value='foo'>foo</option><option value='bar'>bar</option></select>"); 

the example creates an element using jQuery and passes it to jsPlumb. However, in my application I don't use jQuery. Is there an angular way to do this without using jQuery?

Also, instead of passing an element, if I wanted to pass a component like below, how do I do it?

return $("<custom-overlay></custom-overlay>");

I considered using a ViewContainerRef. However, that requires an element which will be the anchor the dynamic components will be added. In this case the "anchor" is a connection line which can be dynamically created.

Is there anyway I can accomplish this without using jQuery? Any help is appreciated.

Upvotes: 2

Views: 1435

Answers (1)

yazz
yazz

Reputation: 301

Below is my solution without using jQuery

I create components dynamically using ViewContainerRef like so -

addOverlayToCanvas(edge) {
    const factory = this.ComponentFactoryResolver.resolveComponentFactory(OverlayComponent);
    const ref = this.overlayContainer.createComponent(factory);
    ref.instance.edge = edge;
    ref.instance['onDeleteEventEmitter'].subscribe((eventInfo) => {
        this.onDelete(eventInfo);
    });
    return ref;
}

and call this method at the time of edge creation and add this element as overlay, like so -

for (let e in edges) {
    let edgeSettings = {
        source: edges[e].sourceId,
        target: edges[e].destinationId
    }
    if(edges[e].overlayId) {
        let overlay = self.addOverlayToCanvas(edges[e]);
        edgeSettings['overlays'] = [
            ['Custom', {
                create:function(component) {
                    return overlay.location.nativeElement;                
                },
                location:0.5,
                id:'customOverlay'
            }]
        ];
    }

    let connection = this.jsPlumbInstance.connect(edgeSettings, this.routeConnectionSettings);
}

Upvotes: 1

Related Questions