angular学习总结十一——动态创建组件并实现交互二

动态组件

上一篇写的是动态创建组件,但是这个组件必须在app.module的entryComponents中声明
现在这个动态组件是包含在module中不用加入entryComponents
app.module.ts

import {
  Component,
  ComponentFactoryResolver,
  ViewChild,
  ViewContainerRef,
  Compiler,
  Injector,
  NgModule,
  ComponentFactory,
  ReflectiveInjector
} from '@angular/core';
import { DynamicComponent } from './dynamic/dynamic.component';
import { COMPILER_PROVIDERS } from '@angular/compiler';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  username = 'zengwe';
  compiler: Compiler;
  @ViewChild('content', { read: ViewContainerRef }) content: ViewContainerRef;
  @ViewChild('contentBymodule', { read: ViewContainerRef }) contentBymodule: ViewContainerRef;
  constructor(private componentFactory: ComponentFactoryResolver, private injector: Injector) { 
    this.injector = ReflectiveInjector.resolveAndCreate(COMPILER_PROVIDERS, injector);
    this.compiler = this.injector.get(Compiler);
  }
  add() {
    const component = this.componentFactory.resolveComponentFactory(DynamicComponent);
    component.inputs.push({propName: 'dd', templateName: 'ss'});
    const com = this.content.createComponent(component);
    console.log(com.instance);
    com.instance.dd = 'dd传的值';
    com.instance.out.subscribe((res) => {
      console.log(res);
    });
  }
  remove() {
    this.content.clear();
  }
  createDynamicComponentByModule(tpl, func = ''): ComponentFactory<any> {
    @Component({
      selector: 'app-dynamic-component',
      template: tpl
    })
    class Dynamic2Component {
      constructor() {
        console.log('DynamicComponent');
        // this.init();
      }
      // init = new Function('functi');
    }
    @NgModule({
      declarations: [Dynamic2Component],
      imports: []
    })
    class DModule {

    }
    return this.compiler.compileModuleAndAllComponentsSync(DModule)
    .componentFactories.find(comfac => comfac.componentType === Dynamic2Component);
    // .then(factory => factory.componentFactories.find(x => x.componentType === Dynamic2Component));
  }
  createOthenDynamicComponent(tpl: string) {
    const componentInstance = this.contentBymodule.createComponent(this.createDynamicComponentByModule(tpl));
    console.log(componentInstance.instance);

  }
}

在constructor中用了

this.injector = ReflectiveInjector.resolveAndCreate(COMPILER_PROVIDERS, injector);

主要还是在编译的时候会出现complier找不到的这种情况
tpl这个参数主要动态添加模板文件,当然可以在Dynamic2Component中运用js中的方法动态生成方法

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值