栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Angular 2.1.0动态动态创建子组件

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Angular 2.1.0动态动态创建子组件

您可以使用以下

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();    }      }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/442191.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号