Я понимаю, что этот вопрос 10 месяцев, но я выложу это только в случае, если кто-либо другой земли здесь ... Я был недавно имея подобную проблему получить Угловое 2 работать с третьей стороной библиотеку JS где Мне нужно было добавить компонент Angular в сторонний lib через html-строки. В конце концов я нашел this answer, и он решил мою проблему.
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: `
<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;
});
}
}
Будет ли компилировать работу $, потому что я использую Angular 2? Правильно ли я говорю: мне нужно создать угловой компонент, скомпилировать его в HTML, а затем добавить в DOM, как добавить любой элемент в DOM? –
Этот вопрос был о Угловом 2. –