0

I have a situation where I need to create and insert components dynamically.

The exact situation is adding markers to a map within Leaflet.

The syntax to do so looks like this:

L.marker(latLng, {title: someTitle, icon: icon}).addTo(this.map).bindPopup(popupContent);

In this case popupContent is either a string of HTML or an HTMLElement object.

I was wondering what the best way to do this with Angular2 would be.

EDIT: A guess a better question is, given that leaflet will be handling the popup anyway, would it be an anti-pattern of sorts if I were to manually compose the HTML (using, for example, a mustache or lodash template) rather than using an Angular component.

0

1 Answer 1

1

You can use something like

   <div [innerHTML]="popupContent"></div>

to add HTML dynamically.

Angular won't process that popupContent and no bindings will be resolved nor any components or directives instantiated even when selectors would match.

See also In RC.1 some styles can't be added using binding syntax

To create components you can use ViewContainerRef.createComponent like explained in Angular 2 dynamic tabs with user-click chosen components

Sign up to request clarification or add additional context in comments.

2 Comments

Not sure how the innerHTML applies to my question (could be missing it). I'm having for bindings, components, etc to be resolved and processed. The main issue is that the element won't be added directly on the DOM (and, as such, can't be a direct child the standard way of adding components using tags and loops, etc won't really apply), but rather, needs to be given to Leaflet to manage. Looking at the ViewContainerRef link, it's not entirely clear how it applies, but I'll dig into it a bit further.
I missed the "leaflet" reference. I don't know what it needs. If you need Angular components and directives to be instantiated and binding resolved [innerHTML]=... is not the right tool. ViewContainerRef.createComponent() allows some variations but I would need more details about your (or leaflets) requirements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.