sajesh Nambiar
sajesh Nambiar

Reputation: 699

ViewChild elementRef undefined even on ngAfterViewInit in Angular 8

I am upgrading the code from Angular 5 to Angular 8 and I am facing a strange issue(scrollContainer and scrollWrapper are both undefined in ngAfterViewInit):

component.ts

@ViewChild('timelineScrollContainer',{ static: true}) set controlElRef(elementRef: ElementRef) {
this.scrollContainer = elementRef;
}

@ViewChild('timelineScroll',{ static: true}) set controlElWrapRef(elementRef: ElementRef) {
this.scrollWrapper = elementRef;
}

ngOnInit() {
this.initTimelineMonths();
this.isLoaded = true;
}

initTimelineMonths() {
  //Populate months array
  this.months = [];
}

ngAfterViewInit() { 
//scrollTimeLineToItem uses the elementRef of scrollContainer 
this.scrollTimeLineToItem(this.monthBoxComponents.last, false);
}

component.html

<div class="timeline-scroll-wrapper" #timelineScroll *ngIf="months">
<div class="bar-labels label-left">
  <span>Federal</span>
  <span>State</span>
  <span>24 Month</span>
</div>
<div class="bar-labels label-right">
  <span>Federal</span>
  <span>State</span>
  <span>24 Month</span>
</div>
<div class="timeline-scroll-container" #timelineScrollContainer>
  <app-month-box *ngFor="let item of months; let i = index;"></app-month-box>
</div>

What is wrong here? Appreciate your inputs.

Thanks

Upvotes: 0

Views: 826

Answers (1)

uminder
uminder

Reputation: 26170

In your component.ts, do the following changes.

@ViewChild('timelineScroll', { static: false }) divTimelineScrollRef: ElementRef<HTMLDivElement>;
@ViewChild('timelineScrollContainer', { static: false }) divTimelineScrollContainerRef: ElementRef<HTMLDivElement>;

...

Upvotes: 1

Related Questions