Progressify
Progressify

Reputation: 93

Determine If component is visible in the screen

I use Nativescript + Angular and this is my code:

<ScrollView class="body" id="scroll" #scroll (scroll)="scrollEvent($event);">
    <StackLayout #stackScroll>

        <ng-template ngFor let-card [ngForOf]="allList">
            <StackLayout [card]="card">

                <my-custom-component [aCard]="card"></my-custom-component>

            </StackLayout>
        </ng-template>

    </StackLayout>
</ScrollView>

I have used this snippet of code and it works great:

https://discourse.nativescript.org/t/how-to-detect-if-component-is-in-screen-view-is-visible/1148/4

I can change the background colour of the "StackLayout" inside the "ng-template".

But I can't access to my custom component variables to modify his behaviour.

For example, if "my-custom-component" is shown, I want to change the property "isShown" in the "card" object passed in the "aCard" attribute.

Thanks to all :)

EDIT1: "isShown" is a custom variable that I have used for this test. My idea is to calculate in the afterScroll function what is the cards visible and pass to aCard the parameter to change his behaviour.

Upvotes: 1

Views: 1436

Answers (2)

Manoj
Manoj

Reputation: 21908

You could find the location of each child component inside ScrollView upon scroll event, comparing the same with the vertical offset will let you know whether the component is really visible on screen.

Here is a Playground example. As you scroll down / up, the background color of visible components will turn green, red otherwise.

onScroll(event: EventData) {
    const scrollView = <ScrollView>event.object,
        verticalOffset = scrollView.verticalOffset,
        height = scrollView.getActualSize().height,
        visibleRange = verticalOffset + height,
        container = <StackLayout>this.container.nativeElement;

    let index = 0;
    container.eachLayoutChild((childView) => {
        const locationY = childView.getLocationRelativeTo(container).y;
        this.cards[index].isShown = locationY >= verticalOffset && locationY <= visibleRange
        index += 1;
    });
}

Upvotes: 1

Narendra
Narendra

Reputation: 4574

You need to update your allList object as NgForOf is bindable, it will update the card and that will reflect in [acard] of your my-custom-component

In the scroll event where you must be playing with relative height you take a unique variable to identify the component that is shown and change the property for that index in allList.

I have created a sample playgrod here where I am changing the text of the custom component Label to isShown if scroll height is greater than 300. The way I am changing the label name, you can have a boolean variable in allList in change that where you have your logic to change the background color of stackLayout. Let me know if you want to update the playgrond.

Upvotes: 0

Related Questions