是否可以手动实例化角度2中的组件

luk*_*uke 7 angular2-components angular

在角度2中,是否可以手动实例化组件A,然后将其传递并在组件B的模板中渲染?

Gün*_*uer 0

是的,这是支持的。ViewComponentRef例如,您需要一个可以通过将其注入构造函数或使用@ViewChild('targetname')查询来获取的 a ,并且ComponentResolver也可以注入 a 。

来自/sf/answers/2542782791/的此代码示例允许动态添加组件*ngFor

@Component({
  selector: 'dcl-wrapper',
  template: `<div #target></div>`
})
export class DclWrapper {
  @ViewChild('target', {read: ViewContainerRef}) target;
  @Input() type;
  cmpRef:ComponentRef;
  private isViewInitialized:boolean = false;

  constructor(private resolver: ComponentResolver) {}

  updateComponent() {
    if(!this.isViewInitialized) {
      return;
    }
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }
   this.resolver.resolveComponent(this.type).then((factory:ComponentFactory<any>) => {
      this.cmpRef = this.target.createComponent(factory)
    });
  }

  ngOnChanges() {
    this.updateComponent();
  }

  ngAfterViewInit() {
    this.isViewInitialized = true;
    this.updateComponent();  
  }

  ngOnDestroy() {
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }    
  }
}
Run Code Online (Sandbox Code Playgroud)