7

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

4

1 回答 1

0

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

这个来自https://stackoverflow.com/a/36325468/217408的代码示例允许例如动态添加组件*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();
    }    
  }
}
于 2016-05-06T04:13:24.603 回答