Angular 2将@Component插入另一个组件的DOM中 [英] Angular 2 insert a @Component into the DOM of another component
问题描述
我有一个组件
import { Component } from '@angular/core';
@Component({
selector: 'test-component',
template: '<b>Content</b>',
})
export class TestPage {
constructor() {}
}
和我有另一个组件:
import { Component } from '@angular/core';
@Component({
selector: 'main-component',
templateUrl: 'main.html',
})
export class MainPage {
constructor() {}
putInMyHtml() {
}
}
main.html:
main.html:
<p>stuff</p>
<div> <!-- INSERT HERE --> </div>
如何动态插入我的 TestPage
组件进入<! - INSERT HERE - >
的区域是以编程方式进行的,就像我运行 putInMyHtml
一样。
How can I dynamically insert my TestPage
component into the area where <!--INSERT HERE-->
is programatically, like when I run putInMyHtml
.
我尝试编辑DOM并插入< test-component>< / test-component>
但是它不显示TestPage模板中的内容文本。
I tried editing the DOM and inserting <test-component></test-component>
but it doesn't display the content text from TestPage's template.
推荐答案
这是 Plunker示例 , ComponentFactoryResolver
首先,您必须正确注册动态组件 TestPage
Firstly you have to register your dynamic component TestPage
properly
app.module.ts
@NgModule({
declarations: [MainPage, TestPage],
entryComponents: [TestPage]
})
替代选项
声明 dy namic-module.ts
import { NgModule, ANALYZE_FOR_ENTRY_COMPONENTS } from '@angular/core';
@NgModule({})
export class DynamicModule {
static withComponents(components: any[]) {
return {
ngModule: DynamicModule,
providers: [
{
provide: ANALYZE_FOR_ENTRY_COMPONENTS,
useValue: components,
multi: true
}
]
}
}
}
并将其导入 app.module。 ts
@NgModule({
imports: [ BrowserModule, DynamicModule.withComponents([TestPage]) ],
declarations: [ MainComponent, TestPage ]
})
然后你的 MainPage
组件可能如下所示:
Then your MainPage
component might look as follows:
import { ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';
@Component({
selector: 'main-component',
template: `
<button (click)="putInMyHtml()">Insert component</button>
<p>stuff</p>
<div>
<template #target></template>
</div>
`
})
export class MainPage {
@ViewChild('target', { read: ViewContainerRef }) target: ViewContainerRef;
constructor(private cfr: ComponentFactoryResolver) {}
putInMyHtml() {
this.target.clear();
let compFactory = this.cfr.resolveComponentFactory(TestPage);
this.target.createComponent(compFactory);
}
}
这篇关于Angular 2将@Component插入另一个组件的DOM中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!