简体   繁体   English

在Angular2中动态插入组件

[英]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. 确切的情况是在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. 在这种情况下, popupContent是HTML字符串或HTMLElement对象。

I was wondering what the best way to do this with Angular2 would be. 我想知道用Angular2做到这一点的最佳方法是什么。

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. 编辑:一个猜测是一个更好的问题,因为无论如何,传单将处理弹出窗口,如果我要手动编写HTML(例如使用小胡子或lodash模板)而不是它,那将是一种反模式吗?使用Angular组件。

You can use something like 您可以使用类似

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

to add HTML dynamically. 动态添加HTML。

Angular won't process that popupContent and no bindings will be resolved nor any components or directives instantiated even when selectors would match. Angular不会处理popupContent ,即使选择器匹配,也不会解析任何绑定,也不会实例化任何组件或指令。

See also In RC.1 some styles can't be added using binding syntax 另请参见在RC.1中,无法使用绑定语法添加某些样式

To create components you can use ViewContainerRef.createComponent like explained in Angular 2 dynamic tabs with user-click chosen components 要创建组件,您可以使用ViewContainerRef.createComponentAngular 2动态选项卡中所述,并通过用户单击所选组件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM