gpt4 book ai didi

javascript - Angular 2.1.0 动态创建子组件

转载 作者:可可西里 更新时间:2023-11-01 02:36:50 24 4
gpt4 key购买 nike

我在 angular 2.1.0 中尝试做的是动态创建应该注入(inject)到父组件中的子组件。例如,父组件是 lessonDetails,它包含所有类(class)的共享内容,例如 Go to previous lessonGo to next lesson 等按钮.基于路由参数,本应是子组件的类(class)内容需要动态注入(inject)到父组件。子组件(类(class)内容)的 HTML 在外部某处定义为纯字符串,它可以是如下对象:

export const LESSONS = {
"lesson-1": `<p> lesson 1 </p>`,
"lesson-2": `<p> lesson 2 </p>`
}

通过 innerHtmlparent component 模板中添加类似以下内容的内容可以轻松解决问题。

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

每次更改路由参数时,父组件的属性 lessonContent 都会发生变化(内容(新模板)将从 LESSON 对象中获取)导致父组件模板被更新。这可行,但 Angular 不会处理通过 innerHtml 注入(inject)的内容,因此无法使用 routerLink 和其他内容。

在新的 Angular 发布之前,我使用 http://blog.lacolaco.net/post/dynamic-component-creation-in-angular-2/ 中的解决方案解决了这个问题。 ,我一直在使用 ComponentMetadataComponentResolver 动态创建子组件,例如:

const metadata = new ComponentMetadata({
template: this.templateString,
});

其中 templateString 作为 Input 属性传递给子组件。 MetaDataComponentResolverangular 2.1.0 中被弃用/删除。

所以问题不仅仅是动态组件的创建,就像一些相关的 SO 问题中所描述的那样,如果我为每个类(class)内容定义组件,问题会更容易解决。这意味着我需要为 100 个不同的类(class)预先声明 100 个不同的组件。已弃用的元数据提供的行为类似于在单个组件运行时更新模板(在路由参数更改时创建和销毁单个组件)。

更新 1: 在最近的 Angular 版本中,所有需要动态创建/注入(inject)的组件都需要在 @NgModule 内的 entryComponents 中预定义。所以在我看来,与上述问题相关,如果我需要有 100 个类(class)(需要动态创建的组件),这意味着我需要预定义 100 个组件

更新二:在更新一的基础上,可以通过ViewContainerRef.createComponent()以如下方式完成:

// lessons.ts
@Component({ template: html string loaded from somewhere })
class LESSON_1 {}

@Component({ template: html string loaded from somewhere })
class LESSON_2 {}

// exported value to be used in entryComponents in @NgModule
export const LESSON_CONTENT_COMPONENTS = [ LESSON_1, LESSON_2 ]

现在在路由参数更改的父组件中

const key = // determine lesson name from route params

/**
* class is just buzzword for function
* find Component by name (LESSON_1 for example)
* here name is property of function (class)
*/

const dynamicComponent = _.find(LESSON_CONTENT_COMPONENTS, { name: key });
const lessonContentFactory = this.resolver.resolveComponentFactory(dynamicComponent);
this.componentRef = this.lessonContent.createComponent(lessonContentFactory);

父模板如下:

<div *ngIf="something" #lessonContentContainer></div>

其中 lessonContentContainer 被修饰为 @ViewChildren 属性并且 lessonContent 被修饰为 @ViewChild 并在中被初始化ngAfterViewInit() 为:

ngAfterViewInit () {
this.lessonContentContainer.changes.subscribe((items) => {
this.lessonContent = items.first;
this.subscription = this.activatedRoute.params.subscribe((params) => {
// logic that needs to show lessons
})
})
}

解决方案有一个缺点,即所有组件 (LESSON_CONTENT_COMPONENTS) 都需要预定义。
有没有一种方法可以使用一个组件并更改它的模板组件在运行时(在路由参数更改时)?

最佳答案

您可以使用以下 HtmlOutlet 指令:

import {
Component,
Directive,
NgModule,
Input,
ViewContainerRef,
Compiler,
ComponentFactory,
ModuleWithComponentFactories,
ComponentRef,
ReflectiveInjector
} from '@angular/core';

import { RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';

export function createComponentFactory(compiler: Compiler, metadata: Component): Promise<ComponentFactory<any>> {
const cmpClass = class DynamicComponent {};
const decoratedCmp = Component(metadata)(cmpClass);

@NgModule({ imports: [CommonModule, RouterModule], declarations: [decoratedCmp] })
class DynamicHtmlModule { }

return compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule)
.then((moduleWithComponentFactory: ModuleWithComponentFactories<any>) => {
return moduleWithComponentFactory.componentFactories.find(x => x.componentType === decoratedCmp);
});
}

@Directive({ selector: 'html-outlet' })
export class HtmlOutlet {
@Input() html: string;
cmpRef: ComponentRef<any>;

constructor(private vcRef: ViewContainerRef, private compiler: Compiler) { }

ngOnChanges() {
const html = this.html;
if (!html) return;

if(this.cmpRef) {
this.cmpRef.destroy();
}

const compMetadata = new Component({
selector: 'dynamic-html',
template: this.html,
});

createComponentFactory(this.compiler, compMetadata)
.then(factory => {
const injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector);
this.cmpRef = this.vcRef.createComponent(factory, 0, injector, []);
});
}

ngOnDestroy() {
if(this.cmpRef) {
this.cmpRef.destroy();
}
}
}

另见 Plunker Example

Example with custom component

对于 AOT 编译,请参阅这些线程

另请参阅github Webpack AOT 示例 https://github.com/alexzuza/angular2-build-examples/tree/master/ngc-webpack

关于javascript - Angular 2.1.0 动态创建子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40060498/

24 4 0
文章推荐: java - 遍历列表中的列表并显示在表中
文章推荐: c++ - 简单的服务器/客户端 boost 示例不起作用
文章推荐: C# 客户端-服务器协议(protocol)/模型问题
文章推荐: java - 如何在 Netty 中分块 List