簡體   English   中英

angular2 RC5中dynamicComponentLoader的替代方案?

[英]Alternative for dynamicComponentLoader in angular2 RC5?

我在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您需要使用CompilercompileComponentAsync()方法。

這是一個簡單的例子:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM