Sub topic 8
on viewport, on interaction and on hover
This chapter covers the three triggers that depend on the user and the page: on viewport, on interaction and on hover. It assumes you have read the earlier chapters on the @defer block, @placeholder, @loading and @error, and the idle, immediate and timer triggers. You should also be comfortable with standalone components and template reference variables such as #name.
What these triggers have in common
The idle, immediate and timer triggers depend only on the browser or the clock. The three triggers in this chapter wait for something to happen to a specific element, called the trigger element. When the event fires, Angular starts loading the deferred chunk and then renders the block.
All three share these rules:
- The trigger element must exist before the deferred content does. Angular can't watch an element that is only rendered by the block it is meant to load.
- If you give no argument, the trigger element is the root element of the
@placeholderblock. - If you give an argument, it is a template reference variable that points at the trigger element.
- A trigger fires at most once. After the block starts loading, Angular removes the listeners.
- You can list several triggers separated by semicolons. The first one to fire wins.
flowchart TD
A[Page renders @placeholder] --> B{Trigger element event}
B -->|enters viewport| C[Start loading chunk]
B -->|click or keydown| C
B -->|mouseenter or focusin| C
C --> D[@loading shown if load is slow]
D --> E[Chunk loaded: swap placeholder for content]
D --> F[Load fails: show @error]The diagram below shows the same flow with its caption and description, in the format the platform draws.
on viewport
on viewport starts loading when the trigger element scrolls into the visible area of the page. Angular uses the browser's IntersectionObserver API for this, so the page does no scroll-handler polling.
The simplest form uses the placeholder as the trigger:
@defer (on viewport) {
<app-comments [postId]="postId" />
} @placeholder {
<div class="comments-placeholder">Comments load as you scroll here.</div>
}Here the <div> is the root element of the placeholder, so it is the element being observed. When it becomes visible, loading starts.
Placeholder rules for this form:
- The placeholder must contain exactly one root element. Text next to the element, or two sibling elements, causes a compile error.
- If the block has no
@placeholder,on viewportwithout an argument can't work, and the compiler reports it.
Watching a different element
You can observe an element that is not the placeholder, for example a heading above the section:
<h2 #commentsHeading>Comments</h2>
@defer (on viewport(commentsHeading)) {
<app-comments [postId]="postId" />
} @placeholder {
<p>Loading area for comments</p>
}When the heading enters the viewport, the comments start loading. This is useful when the placeholder is tiny or hidden, and you want to start earlier than the user reaching the placeholder itself.
Starting early
If loading starts only when the element is visible, the user may see the placeholder or loading block for a moment. Two ways to reduce that:
- Observe an element that sits above the deferred area, as in the example above.
- Add a prefetch trigger so the code is already downloaded when the element becomes visible. Prefetching has its own chapter, but
prefetch on viewportworks with every trigger here.
Recent Angular versions also let you pass IntersectionObserver options, such as rootMargin, to on viewport. Check the API reference for your installed version before relying on this.
on interaction
on interaction waits for the user to act on the trigger element. By default it listens for two events: click and keydown. The keydown listener makes it usable from the keyboard, but only if the element can receive focus.
<button type="button" #showChart>Show chart</button>
@defer (on interaction(showChart)) {
<app-chart />
} @placeholder {
<p>Press the button to see the chart.</p>
}The button is outside the defer block and is referenced by #showChart. When the user clicks it, or focuses it and presses a key, the chart chunk starts loading.
You can also use the placeholder itself. This works well for a "click to load" card:
@defer (on interaction) {
<app-map [location]="venue" />
} @placeholder {
<button type="button" class="map-card">Click to load the map</button>
}Common errors with on interaction
- Using a
<div>as the trigger. A<div>is not focusable, so keyboard users can never firekeydownon it. Use a<button>or addtabindex="0"and a role. A<button>is the better default. - Pointing the reference at an element inside the deferred content. That element does not exist until the block renders, so the trigger could never fire. Angular rejects this at compile time.
- Expecting the trigger to remain active. Once the block is loading or rendered, later clicks on the button do nothing for the defer block. If you need toggling, use an
@if.
on hover
on hover fires when the pointer enters the trigger element or focus moves into it. It listens for mouseenter and focusin. Including focusin means keyboard users who tab to the element get the same behavior as mouse users.
<a routerLink="/reports" #reportsLink>Reports</a>
@defer (on hover(reportsLink)) {
<app-report-preview />
} @placeholder {
<span>Hover over Reports for a preview.</span>
}on hover is a good fit for content that the user is likely, but not certain, to want. Hovering is a cheap signal of intent. The delay between a hover and a click is often a few hundred milliseconds, which is enough to download a small chunk.
Hover on touch devices
Touch screens have no hover. A tap may emit emulated mouse events, but you should not rely on this. If your audience includes phones or tablets, combine triggers:
<button type="button" #details>Show details</button>
@defer (on hover(details); on interaction(details)) {
<app-details-panel />
} @placeholder {
<p>Details appear on hover or click.</p>
}With two triggers, either event starts loading, and the first to fire wins.
Combining triggers with prefetch
Each trigger can be used as a prefetch trigger. The main trigger decides when the block renders, and the prefetch trigger decides when the code downloads. A common pattern is to download on hover and render on click:
<button type="button" #openEditor>Open editor</button>
@defer (on interaction(openEditor); prefetch on hover(openEditor)) {
<app-editor />
} @placeholder {
<p>The editor opens when you click the button.</p>
}With this setup, hovering over the button downloads the editor code. If the user then clicks, the code is already in the browser and the block renders without a loading state. If the user clicks without hovering, for example on a touch device, the chunk downloads at that moment, so the loading block still matters.
Choosing between the three
| Trigger | Fires on | Best for | Watch out for |
|---|---|---|---|
| `on viewport` | Element enters the visible area | Content below the fold, long pages | Placeholder size and layout shift |
| `on interaction` | `click` or `keydown` | Content the user explicitly requests | Non-focusable trigger elements |
| `on hover` | `mouseenter` or `focusin` | Likely-but-not-certain content, previews | Touch devices have no hover |
For content below the fold, on viewport usually fits best. For heavy widgets the user asks for, such as charts or editors, on interaction avoids loading anything until requested. Use on hover mostly as a prefetch trigger or for lightweight previews.
Layout shift with user triggers
All three triggers swap the placeholder for the real content, so a size mismatch moves everything below it. This matters most for on viewport, because the swap happens while the user is looking at that area.
Give the placeholder the same dimensions as the final content:
@defer (on viewport) {
<app-comments [postId]="postId" />
} @placeholder (minimum 300ms) {
<div class="comments-placeholder" style="min-height: 400px"></div>
} @loading (after 100ms; minimum 500ms) {
<div class="comments-placeholder" style="min-height: 400px">Loading comments...</div>
}Keeping the same min-height on the placeholder and loading blocks avoids a jump. The minimum values prevent a flash if the chunk arrives immediately. The timing parameters are covered in an earlier chapter.
A complete example
This standalone component uses all three triggers on one page. It assumes CommentsComponent, ChartComponent and PreviewComponent are standalone components in the same folder.
import { Component } from '@angular/core';
import { CommentsComponent } from './comments.component';
import { ChartComponent } from './chart.component';
import { PreviewComponent } from './preview.component';
@Component({
selector: 'app-dashboard',
imports: [CommentsComponent, ChartComponent, PreviewComponent],
template: `
<h1>Dashboard</h1>
<button type="button" #chartButton>Show chart</button>
@defer (on interaction(chartButton); prefetch on hover(chartButton)) {
<app-chart />
} @placeholder {
<p>Press the button to see the chart.</p>
}
<a href="#preview" #previewLink>Preview</a>
@defer (on hover(previewLink); on interaction(previewLink)) {
<app-preview />
} @placeholder {
<p>Hover or click Preview.</p>
}
@defer (on viewport) {
<app-comments />
} @placeholder {
<div style="min-height: 400px">Comments load as you scroll.</div>
}
`,
})
export class DashboardComponent {}Each of the three imported components is used only inside a @defer block, so the compiler moves each into its own lazy chunk. If any of them were also used outside a defer block in the same file, it would stay in the main bundle.
Gotchas
- With server-side rendering, the server renders the placeholder and none of these triggers fire there. They start working in the browser.
- A reference variable must be in scope. A reference declared inside another
@ifor@forblock is not visible to a defer block outside it. - A
@placeholderthat holds only text, with no element, can't be used as an implicit trigger. - Do not rely on
on hoveras the only way to reach content. Keyboard focus works throughfocusin, but touch users need another trigger.
Exercise
A @defer (on viewport) block has this placeholder: @placeholder { <p>Loading soon</p> <p>Please wait</p> }. The compiler reports an error. Why, and how do you fix it?
Show answer
The implicit trigger for on viewport is the placeholder's root element, so the placeholder must have exactly one root element. Two sibling <p> elements break that rule. Wrap them in a single <div>, or use on viewport(ref) with a reference variable on some other element.
Exercise
You want a heavy editor to download when the user hovers over an "Open editor" button, and to render when the user clicks it. Write the @defer line, assuming the button has the reference #openEditor.
Show answer
@defer (on interaction(openEditor); prefetch on hover(openEditor)). The on interaction trigger renders the block on click or keydown. The prefetch on hover trigger downloads the chunk on mouseenter or focusin, ahead of the click.
Exercise
Why can on interaction fail for keyboard users, and what is the simplest fix?
Show answer
on interaction listens for click and keydown. A keydown event only reaches elements that have focus, so a plain <div> trigger can't be used from the keyboard. Use a <button> as the trigger element, because buttons are focusable and also turn Enter and Space into clicks.