angular2 RC5中dynamicComponentLoader的替代方案

Alternative for dynamicComponentLoader in angular2 RC5?

本文关键字:方案 dynamicComponentLoader RC5 angular2      更新时间:2023-09-26

我要在RC5中创建一个angular2应用程序,我想在其中动态加载组件。

在RC1,我做了同样的使用dynamicComponentLoader:

@Component({
  moduleId: module.id,
  selector: 'generic-component',
  templateUrl: 'generic.component.html',
  styleUrls: ['generic.component.css']
})
export class GenericComponent implements OnInit {
  @ViewChild('target',{read:ViewContainerRef}) target; 
  @Input('component-name') componentName:string;
  @Input('component-info') componentInfo:string;
  @Input('component-model') componentModel:Object;
  keysRegister:string[]=[     
  'users',
  'employee'
  ]; 
  componentNames:string[]=[      
  'UserComponent',
  'EmpComponent'
  ];
  constructor(private dcl:DynamicComponentLoader) {}
  ngOnInit() {
  }
  ngAfterViewInit(){
      let componentIndex=this.keysRegister.indexOf(this.componentName);
      this.dcl.loadNextToLocation(StandardLib[this.componentNames[componentIndex]],this.target)
    .then(ref=>{
        ref.instance.componentModel=this.componentModel;
    });
    console.log("GenericComponent...... "+this.componentName+" Loaded");
  }
}

,当我想加载组件时,我会这样做:

<div *ngIf="columnModel" style="border:1px solid orange">
    <generic-component 
        [component-name]="columnModel.componentName" <!-- I will pass *users* here -->
        [component-model]="columnModel.componentModel"
        [component-info]="columnModel.componentInfo"
    ></generic-component>
</div>

我尝试使用componentResolver,但我不能让它正确工作。输入吗?谢谢。

RC5中,您需要使用Compiler中的compileComponentAsync()方法。

下面是一个简单的例子:

constructor(private _comp: Compiler) {}
ngAfterViewInit(): void {
    this._comp.compileComponentAsync(this.componentModel).then(a => this.target.createComponent(a));
}

下面是我的一个完整的例子:

https://github.com/flauc/ng2-simple-components/blob/master/src/modal/modal.component.ts