Detect when elements are visible
Find out when an element scrolls onto or off the screen, as you would with IntersectionObserver on the web. Use it to render heavy content only when needed, or to track which items the user saw. Lynx calls this exposure (see Glossary).
Choose an API
Watch one element
Add lynxExposure to an element and read its visible() signal:
src/app/feed-item.ts
#exp="lynxExposure"gives the template a reference to the directive.exp.visible()istruewhile the element is on screen andfalseotherwise. It starts asfalse.- The element must have a size and not be fully transparent. Inside a
<scroll-view>or<list>, it counts as visible when it overlaps the visible part of the scroll area. - The directive cleans up after itself when the element is destroyed.
The directive switches content in and out as the user scrolls. To create a component the first time it appears and keep it, combine lynxExposure with @defer.
Track impressions across the page
Give each element you want to track an exposure-id, then read the batches from LynxGlobalExposure:
src/app/home.ts
exposure-idmarks an element for tracking. Use[attr.exposure-id]to set it from data.exposure-sceneis an optional label for grouping, such as the screen name.- Lynx checks visibility about 20 times a second and reports changes in batches.
exposures()holds the latest batch of elements that became visible.disexposures()holds the latest batch that left the screen.- Each signal holds only the latest batch. To count impressions, or to track everything that's on screen, add each batch to your own state in an
effect().
Pause and resume tracking
src/app/tracking-toggle.ts
stopExposure()stops Lynx's visibility checks. By default, Lynx first reports every visible element as having left. Pass{ sendEvent: false }to skip that.active()is a signal that'sfalsewhile paused.
Related
- Exposure API reference: every signal, method and event field
@defer: create a component when it first scrolls into view- Threads: where your code runs
- Lynx's exposure guide: attributes such as
exposure-areathat change when an element counts as visible
