简体   繁体   English

angular2 RC5中dynamicComponentLoader的替代方案?

[英]Alternative for dynamicComponentLoader in angular2 RC5?

I am creating an angular2 app in RC5 in which I want to load Components Dynamically. 我在RC5中创建一个angular2应用程序,我想在其中动态加载组件。

in RC1 , I did same using dynamicComponentLoader as: 在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");

  }

}

and whenever I want to load the component I would do: 每当我想加载组件时,我会这样做:

<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>

I tried using componentResolver but I am not able to get it work correctly. 我尝试使用componentResolver,但我无法正常工作。 Any Inputs? 任何输入? Thanks. 谢谢。

In RC5 you need to use the compileComponentAsync() method from the Compiler . RC5您需要使用CompilercompileComponentAsync()方法。

Here is a quick example: 这是一个简单的例子:

constructor(private _comp: Compiler) {}

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

And here is a complete example from a library of mines: 以下是矿山图书馆的完整示例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM