1

I'm having some trouble figuring out why I'm getting this error. I'm familiar with @ViewChild() and Angular's lifecycle hooks so I've tried every "right way" of doing things which all render without a problem on the page but still throw this error. I came across this Stackoverflow question which has a few solutions and links to information revolving around the issue however nothing I try makes it go away.

My component looks like this

export class BoxSizeVariantComponent implements OnInit, AfterViewInit {

  @Input() Width: string = '0px';
  @Input() Title: string = '--';

  @ViewChild('sizeShell', {static: false}) SizeShell! : ElementRef<HTMLElement>;

  Size: number = 0;

  constructor(private zone: NgZone) { }

  ngOnInit(): void {
    
    
  }
  
  ngAfterViewInit(): void {

    const BoxObserver = new ResizeObserver((entry) =>{
      this.zone.run(()=> { this.updateSize();});
    });
    
    BoxObserver.observe(this.SizeShell.nativeElement);
    
  }

  private updateSize(): void {
    this.Size = this.SizeShell.nativeElement.offsetWidth;
  }

}

and the template

<p>{{Title}}</p>
<section class="mainShell">
    <article #sizeShell class="sizeShell" [ngStyle]="{'width': Width}">
        <p>
            {{Size}}px
        </p>
    </article>
    <p>
        {{Size}}px
    </p>
</section>

The component I use this in gets embedded into an <iframe> with Renderer2 and has encapsulation set to ViewEncapsulation.shadowDom so the styling loads. I do this same thing in other components using @ViewChild() and don't get any errors. I tried changing the change detection to onPush and using ChangeDetectorRef to force the check to occur. I've switched static back and forth between true and false, I've tried using the AfterContentChecked hook, I don't know what else to try. Does anyone have any clue as to why this is happening?

Optiq
  • 2,835
  • 4
  • 33
  • 68

0 Answers0