如何在JQuery中动态注入AngularJS 2组件? [英] How can I inject an AngularJS 2 component dynamically in JQuery?

查看:72
本文介绍了如何在JQuery中动态注入AngularJS 2组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an Angular2 application and consumes JQuery in some parts of the application. A sample code is below:

$(function(){
    var id = 'post349';
    var data = 'The quick brown fox...';
    $('<div><angular-test></angular-test></div>').attr('id',id).addClass('myclass').html(data).appendTo('#records_wrapper');
    // Looking for the AngularJS 2.0 API to dynamically inject <angular-test> component.
});

#records_wrapper {
    background-color:red;
    border:4px solid orange;
}

#records_wrapper div {
    background-color:green;
}

.myclass {
    border:2px solid yellow;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="records_wrapper"></div>

<angular-test>是示例角度分量.我面临的问题是组件没有扩展到它的组件,这意味着它没有被处理,因此它在DOM中仍为<angular-test></angular-test>.

The <angular-test> is a sample angular component. The problem that I'm facing is component does not expands to it's component which means it is not processed, so it stay as <angular-test></angular-test> in the DOM.

在jQuery操纵DOM后,如何动态注入名为<angular-test>的Angular2组件?我应该使用什么Angular API?

How can I inject an Angular2 component called <angular-test> dynamically after the DOM is manipulated by JQuery? What Angular API I should use?

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

PS. In the example I have not included the code for the angular component.

推荐答案

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

I realize this question is 10 months old but I'll post this just in case anyone else lands here... I was recently having a similar problem getting Angular 2 to work with a third party js library where I needed to add an Angular component to the third party lib via html strings. I eventually found this answer to a similar question and it solved my problem.

Radim很好地解释了如何动态加载组件,但是我最终对其代码进行了一些修改,以使组件加载更加清晰.

Radim gives an excellent explanation of how to dynamically load components, but I ended up modifying his code slightly to show the component loading a little clearer.

我只更改了dynamic.component.holder文件,使其具有一个使用addComponent()函数加载组件的按钮,如下所示:...

I only changed the dynamic.component.holder file to have a button that loads the component with the addComponent() function like so... Check out this plunker for all the code.

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: `
<div>
  <h1>Dynamic content holder</h1>
  <hr />
  <div #dynamicContentPlaceHolder></div>
  <hr />
  change description <input [(ngModel)]="entity.description" style="width:500px" />
  <button (click)="addComponent()">Add Component</button>
</div>
`,
  providers: [CustomComponentBuilder], 
}) 
export class DynamicHolder implements OnInit
{  
    public entity: { description: string };
    dynamicComponent: IHaveDynamicData;

    // reference for a <div> 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<IHaveDynamicData>) =>
        {
            // 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中动态注入AngularJS 2组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆