确定组件在屏幕上是否可见

时间:2019-01-24 09:54:52

标签: nativescript visibility show-hide angular2-nativescript nativescript-angular

我使用Nativescript + Angular,这是我的代码:

{{1}}

我已经使用了这段代码,效果很好:

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

我可以在“ ng-template”中更改“ StackLayout”的背景颜色。

但是我无法访问我的自定义组件变量来修改他的行为。

例如,如果显示“ my-custom-component”,我想更改在“ aCard”属性中传递的“ card”对象中的属性“ isShown”。

感谢所有人:)

EDIT1: “ isShown”是我用于此测试的自定义变量。我的想法是在afterScroll函数中计算可见的卡片,然后将参数传递给aCard以更改其行为。

2 个答案:

答案 0 :(得分:0)

您需要更新allList对象,因为NgForOf是可绑定的,它将更新卡片,这将反映在您的my-custom-component的[acard]中

在滚动事件中,您必须以相对的高度进行游戏,您将使用一个唯一变量来标识显示的组件并更改allList中该索引的属性。

我创建了一个示例playgrod here,在其中将自定义组件Label的文本更改为isShown,如果滚动高度大于300。在更改标签名称的方式中,您可以使用布尔变量在allList中进行更改,即您有逻辑来更改stackLayout的背景颜色。让我知道您是否要更新游戏地。

               

答案 1 :(得分:0)

滚动事件发生时,您可以在ScrollView中找到每个子组件的位置,将其与垂直偏移进行比较可以让您知道该组件在屏幕上是否真正可见。

Here is a Playground example。向下/向上滚动时,可见组件的背景颜色将变为绿色,否则变为红色。

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;
    });
}
相关问题