Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating height of the child component dynamically

I'm developing an Angular application and I'm facing some issues.

I am in a situation where I have to load multiple child components inside a parent container component.The child component is loaded one below the other. I want to load 'n' number of components till the scroll is visible so that I can handle lazy loading of child components. As of now, I'm trying to use the following condition.

while (window.screen.height > 
   this.elementRef.nativeElement.getBoundingClientRect().height) 
   {
      this.child= this.childSet.slice(0, this.count+1);
   }

and the html code is as follows

<child*ngFor="let child of childSet" [value]="child " [column-size]="child .size ? child .size : 12"></child>

but it's going on in an infinite loop and I don't know why but I guess the view is not rendered as fast as the while loop. So how to resolve this issue.Please help.

like image 416
Vikhyath Maiya Avatar asked Feb 15 '18 09:02

Vikhyath Maiya


3 Answers

I have created a demo that provides a solution to your issue. Here: https://stackblitz.com/edit/angular-9hd2no.
Instead of using a loop, I put your logic inside an interval which will keep repeating till stopCondition is true. I have also added some classes in styles.css and app.component.css to make the parent component height grow as the number of child component increases. Hope this helps.

like image 193
NiK648 Avatar answered Nov 18 '22 22:11

NiK648


Maybe try using trackBy for you *ngFor this way it won't refresh all the elements and instead it will just add a new one whenever you change the collection. It can be a solution to your infinite loop.

I'd try something like this

  trackByFn(index, item) {
    return index;
  }

and the html

<child *ngFor="let child of childSet; trackBy: trackByFn" [value]="child " [column-size]="child .size ? child .size : 12"></child>
like image 31
SebOlens Avatar answered Nov 18 '22 21:11

SebOlens


GetBoundingClientRect returns perfect value only after rendering finish. So you should render one element at a time and append element only if scroll is not visible.

like image 2
Rajdip Patel Avatar answered Nov 18 '22 20:11

Rajdip Patel