NRaf
NRaf

Reputation: 7549

Dynamically inserting components in Angular2

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.

Upvotes: 0

Views: 1087

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657338

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

Upvotes: 1

Related Questions