1

我试图引用我在使用应用程序期间添加的动态模板,但 view child 的值始终未定义,所以我问我可以在 View Init 之后实例化它吗?
谢谢 。我正在使用 Dragula 库,并且我想在放置拖动的元素时创建一个组件,问题是要创建的组件用于在同一页面中加载的许多组件中,所以我想注入一个“cabled” html 元素在其中的 on 中具有不同的局部变量,我想使用视图子项稍后访问该子项。

@ViewChild('viewerheader',{ read: ViewContainerRef }) viewerContainer;
  constructor(private dragulaService: DragulaService,private componentFactoryResolver: ComponentFactoryResolver) {
    dragulaService.drop.subscribe((value) => {
      //console.log('dropped header sunbscribed' , value ) ;
      this.onDrop(value.slice(1));

    }); 
  }

ngOnInit() { 
  this.element = document.getElementById('sectionheader0');
       console.log ('got element' ,this.element );
       $(this.element).append('<ng-template  #viewerHeader></ng-  template>');
     }
private onDrop(args) {
    let [e, target ,source,el] = args;
    this.createComponent(e.id);
  }
  
  
createComponent(id : string){
    //this.viewerContainer.clear(); 
    const factory = this.componentFactoryResolver.resolveComponentFactory(Viewer);
    const componentRef = this.viewerContainer.createComponent(factory);
    componentRef.instance.id = id;
    console.log('create Compnent called + Id' + id);
    
    console.log('create component' + id );
    } 

4

1 回答 1

0

请试试这个方法。在 AfterViewInit 钩子中订阅 ViewChild 的更改。

 ngAfterViewInit() {
    this.viewerContainer.changes.subscribe(() => {
   // do anything here since you are sure that view child is defined

     });;
  }
于 2017-11-28T09:07:57.703 回答