angular2 RC5中dynamicComponentLoader的替代方案?

时间:2016-08-27 05:25:18

标签: javascript angular typescript

我正在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,但我无法正常使用它。 任何输入? 感谢。

1 个答案:

答案 0 :(得分:-1)

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

这是一个简单的例子:

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

相关问题