如何在JQuery中动态注入AngularJS 2组件?

我有一个Angular2应用程序,并在应用程序的某些部分使用JQuery。 示例代码如下:

$(function(){ var id = 'post349'; var data = 'The quick brown fox...'; $('
').attr('id',id).addClass('myclass').html(data).appendTo('#records_wrapper'); // Looking for the AngularJS 2.0 API to dynamically inject component. });
 #records_wrapper { background-color:red; border:4px solid orange; } #records_wrapper div { background-color:green; } .myclass { border:2px solid yellow; } 
  

是样本角度分量。 我面临的问题是组件没有扩展到它的组件,这意味着它没有被处理,因此它在DOM中保持为

在JQuery操作DOM之后,如何动态地注入一个名为的Angular2组件? 我应该使用什么Angular API?

PS。 在示例中,我没有包含角度分量的代码。

我意识到这个问题已经有10个月了,但是我会发布这个以防万一其他人来到这里…我最近遇到类似的问题让Angular 2与第三方js库一起工作,我需要添加一个Angular组件通过html字符串到第三方lib。 我最终找到了一个类似问题的答案 ,它解决了我的问题。

Radim给出了如何动态加载组件的一个很好的解释,但我最终修改了他的代码,以显示组件加载更清晰。

我只更改了dynamic.component.holder文件,使其具有一个按钮,该按钮使用addComponent()函数加载组件,如此…请查看此plunker以获取所有代码。

 import {Component,OnInit} from '@angular/core'; import {ComponentResolver,ViewChild,ViewContainerRef} from '@angular/core'; import {FORM_DIRECTIVES} from "@angular/common"; import { IHaveDynamicData, CustomComponentBuilder } from './custom.component.builder'; @Component({ selector: 'dynamic-holder', template: ` 

Dynamic content holder



change description
`, providers: [CustomComponentBuilder], }) export class DynamicHolder implements OnInit { public entity: { description: string }; dynamicComponent: IHaveDynamicData; // reference for a
with # @ViewChild('dynamicContentPlaceHolder', {read: ViewContainerRef}) protected dynamicComponentTarget: ViewContainerRef; // ng loader and our custom builder constructor( protected componentResolver: ComponentResolver, protected customComponentBuilder: CustomComponentBuilder ) {} public ngOnInit(){ // just init the entity for this example this.entity = { description: "The description of the user instance, passed as (shared) reference" }; // dynamic template built (TODO driven by some incoming settings) var template = this.customComponentBuilder .CreateTemplate(); // now we get built component, just to load it this.dynamicComponent = this.customComponentBuilder .CreateComponent(template, FORM_DIRECTIVES); } public addComponent() { // we have a component and its target this.componentResolver .resolveComponent(this.dynamicComponent) .then((factory: ng.ComponentFactory) => { // Instantiates a single {@link Component} and inserts its Host View // into this container at the specified `index` let dynamicComponent = this.dynamicComponentTarget.createComponent(factory, 0); // and here we have access to our dynamic component let component: IHaveDynamicData = dynamicComponent.instance; component.name = "The name passed to component as a value"; component.entity = this.entity; }); } }

为什么使用jquery创建元素使用角度方式。

 var newDirective = angular.element('
'); element.append(newDirective); $compile(newDirective)($scope);