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.
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.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With