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.

NRaf
  • 7,407
  • 13
  • 52
  • 91

1 Answers1

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

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 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. – NRaf Jun 01 '16 at 21:39
  • 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. – Günter Zöchbauer Jun 02 '16 at 04:37