how can i get the height of a dynamically created div and send it to a sibling component?

The reason this attempt:

alertActive = new BehaviorSubject(0);
setAlertHeight(value:number){
  this.alertActive.next(value)
}

triggered the height to be set even when the alert was not active was because you used a BehaviorSubject rather than just a Subject. A BehaviorSubject provides an initial value (0 in your case), so immediately upon subscription the subscriber will receive that initial value (or the latest emitted value).

So you were on the right track, you just needed to use a regular Subject instead because then subscribers won’t receive any values until the Subject emits.

So your service could look like this:

private _alertActive = new Subject<number>();
get alertActive(): Observable<number> {
  return this._alertActive.asObservable();
}

setAlertHeight(height: number) {
  this._alertActive.next(height);
}

(Note that the Subject is a private member but is exposed via a getter as an Observable. In general, subscribers shouldn’t have access to the raw Subject unless they’ll also be emitting values from it.)

And your child-2 component would subscribe to it like so:

this.service.alertActive.subscribe((height: number) => {
  this.actualHeight -= height;
});

You were also on the right track using ViewChildren and subscribing to its changes, but it might be simpler if you reference the ElementRefs rather than the ViewContainerRefs. That would look like this:

import { NgbCarousel } from "@ng-bootstrap/ng-bootstrap";

@ViewChildren(NgbCarousel, { read: ElementRef }) carousels: QueryList<ElementRef>;


ngAfterViewInit() {
  this.carousels.changes.subscribe((els: QueryList<ElementRef>) => {
    const height = els.first ? els.first.nativeElement.offsetHeight : 0;
    this.service.setAlertHeight(height);
  });
}

Here’s a StackBlitz showing it working with this approach.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top