简体   繁体   中英

instantiate @ViewChild on AfterViewInit angular 2

i was trying to make reference to a dynamic template which i add during the usage of the app but the value of view child is always undefined , so i was asking can i instantiate it on After View Init ?
thanks . i'm using dragula library and i want to create a component when i drop a dragged element , the problem is that the component to be created is used in many components that are loaded in the same page so i want to inject a 'cabled ' html element with a different local variable in the on in it and i want to use the view child to have access to that child later .

 @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 ); } 

Please try this method. Subscribe to changes of ViewChild in AfterViewInit hook.

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

     });;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM