Vikhyath Maiya
Vikhyath Maiya

Reputation: 3192

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.

Upvotes: 12

Views: 2873

Answers (3)

Rajdip Patel
Rajdip Patel

Reputation: 551

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.

Upvotes: 2

Sebastian Oleński
Sebastian Oleński

Reputation: 538

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>

Upvotes: 2

NiK648
NiK648

Reputation: 1486

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.

Upvotes: 3

Related Questions