> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# Detect when elements are visible

Find out when an element scrolls onto or off the screen. Use it to render heavy content only when needed, or to track which items the user saw. Lynx calls this **exposure** (see [Glossary](/guide/glossary.md#exposure)).

## Choose an API

| You want to                                                         | Use                                                                                                        |
| ------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| Change what one element shows when it becomes visible               | The [`lynxExposure` directive](#watch-one-element): a `visible()` signal per element                       |
| Record impressions across the whole page, for example for analytics | The [`LynxGlobalExposure` service](#track-impressions-across-the-page): batched events for tagged elements |
| Watch elements from code, or use a library written for the browser  | [`IntersectionObserver`](#use-intersectionobserver), as on the web                                         |

All three follow the element as it scrolls and moves, not whether the app is in front.

On iOS, an element stays on screen while the app is in the background. It also stays on screen with Control Center, Notification Center or the app switcher over the app. A browser does the same when its window is covered.

## Watch one element

Add `lynxExposure` to an element and read its `visible()` signal:

```typescript title="src/app/feed-item.ts"
import { Component } from '@angular/core';
import { LYNX_ELEMENTS, LynxExposure } from '@blotch/angular-lynx'; // [!code highlight]

@Component({
  selector: 'app-feed-item',
  imports: [LYNX_ELEMENTS, LynxExposure], // [!code highlight]
  template: `
    <view lynxExposure #exp="lynxExposure" style="height: 200px">
      @if (exp.visible()) {
        <image
          src="https://example.com/photo.jpg"
          style="width: 100%; height: 200px"
        />
      } @else {
        <view style="height: 200px; background-color: #e4e4e7" />
      }
    </view>
  `,
})
export class FeedItem {}
```

- **`#exp="lynxExposure"`** gives the template a reference to the directive.
- **`exp.visible()`** is `true` while the element is on screen and `false` otherwise. It starts as `false`.
- **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`](/guide/defer.md).

## Use `IntersectionObserver`

`IntersectionObserver` takes Lynx elements, so code and libraries written for the browser work unchanged. Observe an element from its `ElementRef`:

```typescript title="src/app/scene-frame.ts"
import {
  Component,
  DestroyRef,
  ElementRef,
  inject,
  signal,
} from '@angular/core';
import { LYNX_ELEMENTS } from '@blotch/angular-lynx';

@Component({
  selector: 'app-scene-frame',
  imports: [LYNX_ELEMENTS],
  template: `<text>{{ onScreen() ? 'Drawing' : 'Paused' }}</text>`,
})
export class SceneFrame {
  readonly onScreen = signal(false);

  constructor() {
    const observer = new IntersectionObserver((entries) => {
      for (const entry of entries) this.onScreen.set(entry.isIntersecting); // [!code highlight]
    });
    observer.observe(inject(ElementRef).nativeElement); // [!code highlight]
    inject(DestroyRef).onDestroy(() => observer.disconnect());
  }
}
```

- **It reports each element once observing starts**, as a browser does, then each time the element comes into view or leaves it. The first report waits for the element's first layout. After that, the same rules as `lynxExposure` decide what counts as visible.
- **Entries have the browser's fields**: `isIntersecting`, `intersectionRatio`, `boundingClientRect`, `intersectionRect`, `rootBounds` and `target`. The boxes are measured when Lynx notices the change, so an element scrolling into view reports a small `intersectionRatio`.
- **In tests**, [`fireEvent.uiappear()` and `fireEvent.uidisappear()`](/api/testing-library/event-reference.md#coming-into-view) bring an element into view and take it out.
- **It's in your app's bundle only when the app uses it.** The build adds it for a file of your app or its libraries that names `IntersectionObserver` or has an `@defer (on viewport)` block. Code that looks it up by a name it builds at runtime finds it missing, unless another file names it. In that case, call `ɵenableIntersectionObserver()` from `@blotch/angular-lynx` first.

### Thresholds, margins and a root

`threshold`, `rootMargin`, `scrollMargin` and `root` work as they do in the browser:

```typescript
// Count a video as seen once half of it is on screen.
const seen = new IntersectionObserver(
  ([entry]) => entry.intersectionRatio >= 0.5 && this.markSeen(),
  { threshold: 0.5 },
);

// Load the next page while the end of the list is still 400px away.
// `list` is viewChild.required<ElementRef>('list'), for a <list #list>.
const nearEnd = new IntersectionObserver(
  ([entry]) => entry.isIntersecting && this.loadMore(),
  { root: this.list().nativeElement, rootMargin: '0px 0px 400px 0px' },
);

// Start loading an image 300px before it scrolls into view, in whatever
// <scroll-view> or <list> it's in.
const ahead = new IntersectionObserver(
  ([entry]) => entry.isIntersecting && this.load(),
  { scrollMargin: '300px' },
);
```

- **`threshold`** reports each time the visible part of the element crosses one of the values, with its `intersectionRatio` then. As in Chrome and Safari, `isIntersecting` is `true` only once the element has reached a threshold: with `threshold: 1`, a half-visible element isn't intersecting.

- **`rootMargin`** grows the root's box before the element is checked against it, or shrinks it with negative values. It takes `px`, another absolute unit (`in`, `cm`, `mm`, `Q`, `pt` or `pc`) or `%`. Percentages are of the root's height for the top and bottom, and of its width for the sides. Every value needs its unit, `0` too, as in the spec, Chrome and Firefox. On iOS and Android, a bare `0` throws a `SyntaxError`. The observer's `rootMargin` reads an absolute length back in px, and a percentage as a percentage: `'1in 10%'` reads `'96px 10% 96px 10%'`. The web preview keeps the browser's own observer. There, Safari also takes a bare `0`, and Firefox takes only `px` and `%`. So write margins in `px` and `%` to run the same everywhere.

- **`root`** is an element around the observed one, such as a `<scroll-view>` or `<list>`. The element is checked against the root, clipped by the scroll containers between them, and not against the screen.

- **`rootMargin` grows only the root**, as in the browser, and not the scroll containers inside it. To load ahead in a `<scroll-view>` or `<list>`, make it the root, as `nearEnd` does above, or use `scrollMargin`.

- **`scrollMargin`** grows every scroll container between the element and the root (`<scroll-view>`, `<list>`, `<viewpager>` and `<scroll-coordinator>`), and the root too when it scrolls. With no root, as for `ahead` above, it also grows the page, as the browser grows the viewport, so it loads ahead in a scroll-view that fills the screen too. It takes the same units as `rootMargin`, each percentage of the box it grows: its height for the top and bottom, and its width for the sides. `rootBounds` doesn't include it. `@defer (on viewport({ scrollMargin: '300px' }))` uses it to [create a block before it scrolls into view](/guide/defer.md#load-before-it-comes-on-screen).

- **With any of these options, the observer measures the element itself.** It measures:

  - when the element is laid out
  - when it comes into view or leaves
  - 20 times a second while a scroll container between it and the root scrolls
  - when one of those scroll containers is laid out again, as one that grows or shrinks moves the edge that clips the element

  That's a measurement per observed element each time. So leave the options out when all you need is to know when an element comes into view and leaves.

- **In tests**, `fireEvent.uiappear()` brings all of the element into view (an `intersectionRatio` of 1). `fireEvent.uidisappear()` takes all of it out. It's all or nothing because the test environment has no layout to measure.

## Track impressions across the page

Give each element you want to track an `exposure-id`, then read the batches from `LynxGlobalExposure`:

```typescript title="src/app/home.ts"
import { Component, effect, inject } from '@angular/core';
import { LYNX_ELEMENTS, LynxGlobalExposure } from '@blotch/angular-lynx'; // [!code highlight]

@Component({
  selector: 'app-home',
  imports: [LYNX_ELEMENTS],
  template: `
    <scroll-view scroll-orientation="vertical" style="height: 100%">
      <view
        exposure-id="promo-banner"
        exposure-scene="home"
        style="height: 300px"
      >
        <text>Promotion</text>
      </view>
      @for (product of products; track product) {
        <view
          [exposure-id]="product"
          exposure-scene="home"
          style="height: 120px"
        >
          <text>{{ product }}</text>
        </view>
      }
    </scroll-view>
  `,
})
export class Home {
  readonly products = ['shoes', 'hats', 'bags', 'scarves'];
  readonly #exposure = inject(LynxGlobalExposure); // [!code highlight]

  constructor() {
    effect(() => {
      for (const seen of this.#exposure.exposures()) {
        console.log('Seen:', seen.exposureID, 'in', seen.exposureScene);
      }
    });
  }
}
```

- **`exposure-id`** marks an element for tracking. Bind `[exposure-id]` to set it from data. **`exposure-scene`** is 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

```typescript title="src/app/tracking-toggle.ts"
import { Component, inject } from '@angular/core';
import { LYNX_ELEMENTS, LynxGlobalExposure } from '@blotch/angular-lynx';

@Component({
  selector: 'app-tracking-toggle',
  imports: [LYNX_ELEMENTS],
  template: `
    <view (bindtap)="toggle()">
      <text>{{
        exposure.active() ? 'Pause tracking' : 'Resume tracking'
      }}</text>
    </view>
  `,
})
export class TrackingToggle {
  readonly exposure = inject(LynxGlobalExposure);

  toggle(): void {
    if (this.exposure.active()) {
      this.exposure.stopExposure(); // [!code highlight]
    } else {
      this.exposure.resumeExposure(); // [!code highlight]
    }
  }
}
```

- **`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's `false` while paused.

## Related

- [Exposure API reference](/api/angular-lynx/exposure.md): every signal, method and event field
- [`@defer`](/guide/defer.md): create a component when it first scrolls into view
- [Threads: where your code runs](/guide/concepts/threads.md)
- [Lynx's exposure guide](https://lynxjs.org/guide/interaction/visibility-detection/exposure-ability.html): attributes such as `exposure-area` that change when an element counts as visible
