【问题标题】:Is it possible to manually instantiate component in angular 2是否可以在角度 2 中手动实例化组件
【发布时间】:2016-05-06 02:51:33
【问题描述】:

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

【问题讨论】:

  • 欢迎来到 SO,请查看此URL它将帮助您提高您的问题内容质量

标签: angular angular2-components


【解决方案1】:

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

来自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();
    }    
  }
}

【讨论】:

  • 此示例不允许使用数据实例化组件。
  • 不确定你的意思。链接答案中更完整的示例显示了如何传入和传出数据。
猜你喜欢
  • 2019-03-07
  • 1970-01-01
  • 2018-04-15
  • 2020-05-13
  • 2019-02-18
  • 2022-01-06
  • 1970-01-01
  • 2020-11-24
  • 1970-01-01
相关资源
最近更新 更多