Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 74 ยท Components in Depth

Template Refs, View Queries and Host Bindings

Learn Angular template reference variables, viewChild, viewChildren, contentChild, ElementRef, host metadata and hostDirectives with runnable stand-ins.

Most of Angular is declarative: you bind data in the template and the framework updates the page. Now and then you need to reach into the template instead. You want to focus an input when a dialog opens, call a method on a child component, read the width of an element, or give the component's own tag a class and an ARIA attribute. Angular has a small, tidy toolbox for these jobs: template reference variables, view and content queries, ElementRef, host bindings, and host directives.

This lesson covers each of them with real Angular code (read-only on this site) and two runnable stand-ins that model the ideas in plain TypeScript and JavaScript. The stand-ins are not Angular's implementation; they exist so you can see what a query returns and what a host binding does.

Template reference variables

A template reference variable is a name you attach to an element with #. You can use it anywhere in the same template:

HTML
<input #nameInput type="text" placeholder="Your name" />
<button type="button" (click)="greet(nameInput.value)">Greet</button>

What the variable refers to depends on where you put it:

  • On a plain element, it is the DOM element (HTMLInputElement here).
  • On a component's tag, it is the component instance, so #player on <app-player> lets the template call player.pause().
  • On a directive, with #ref="exportAs", it is the directive instance. For example #form="ngForm" gives you the NgForm directive.
  • On an <ng-template>, it is a TemplateRef (content projection uses this).

A reference variable is only visible inside its own template (and inside nested blocks such as @if). It cannot be read from the component class. For that you need a query.

Querying the view with viewChild

viewChild() is a function that returns a signal holding the first match in the component's own template. You can look an element up by its template reference name, or find a component or directive by its class:

TypeScript
import { Component, ElementRef, afterNextRender, viewChild } from '@angular/core';

@Component({
  selector: 'app-search-box',
  template: `
    <input #box type="search" placeholder="Search" />
    <button type="button" (click)="clear()">Clear</button>
  `,
})
export class SearchBoxComponent {
  private box = viewChild.required<ElementRef<HTMLInputElement>>('box');

  constructor() {
    afterNextRender(() => this.box().nativeElement.focus());
  }

  clear(): void {
    const input = this.box().nativeElement;
    input.value = '';
    input.focus();
  }
}

A few facts you need to get right:

  • The result is a Signal<T | undefined>. It is undefined until the view has rendered, and again if the matching element is removed (for example by an @if).
  • viewChild.required() returns a Signal<T> instead. Reading it when there is no match throws an error, so it is for things that are always present. Read it after rendering (in an event handler, in afterNextRender, or inside an effect), not in the constructor body.
  • Queries are reactive. If the match appears later (an @if turns true), the signal updates, and any computed or effect that reads it re-runs.
  • A query by name returns an ElementRef for a plain element, but the component instance when the #ref sits on a component tag. The read option picks something else: viewChild('box', { read: ElementRef }).

viewChildren() is the plural. It returns a signal of a read-only array of all matches, in template order:

TypeScript
import { Component, viewChildren } from '@angular/core';
import { ItemComponent } from './item.component';

@Component({
  selector: 'app-item-list',
  imports: [ItemComponent],
  template: `
    @for (name of names; track name) {
      <app-item [label]="name" />
    }
  `,
})
export class ItemListComponent {
  names = ['Ada', 'Grace', 'Linus'];
  items = viewChildren(ItemComponent);

  collapseAll(): void {
    this.items().forEach((item) => item.collapse());
  }
}

The older decorator forms @ViewChild and @ViewChildren still exist and behave like the functions, but they give you plain properties that are filled in during lifecycle hooks. The signal versions are easier to reason about, and they are the recommended style for new code.

View queries vs content queries

There are two places a child can live:

  • In the component's own template: that is the view, queried with viewChild / viewChildren.
  • Between the component's tags in the parent's template: that is projected content, queried with contentChild / contentChildren.
flowchart TD
  subgraph Parent["Parent template"]
    T["app-tabs"] --> A["app-tab (projected)"]
    T --> B["app-tab (projected)"]
  end
  subgraph Tabs["app-tabs own template"]
    P["div #panel"]
  end
  T -.->|"contentChildren(TabComponent)"| A
  T -.->|"contentChildren(TabComponent)"| B
  T -.->|"viewChild('panel')"| P

Content queries find what the parent projected in; view queries find what the component's own template contains.

TypeScript
@Component({
  selector: 'app-tabs',
  template: `
    <nav>
      @for (tab of tabs(); track tab) {
        <button type="button">{{ tab.title() }}</button>
      }
    </nav>
    <div #panel><ng-content /></div>
  `,
})
export class TabsComponent {
  tabs = contentChildren(TabComponent);
  panel = viewChild<ElementRef<HTMLElement>>('panel');
}

contentChildren only finds direct children of the host by default. Pass { descendants: true } to also find matches nested deeper in the projected markup. contentChild finds descendants by default.

The stand-in below models both kinds of query over a small tree of elements. Elements can have a template ref name or a component type, and the helpers search a subtree. Note how a required query fails when nothing matches.

TypeScript Stand-in: viewChild and viewChildren over a tree

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The same query function returns different results as the tree changes. Angular's signals do the same thing with caching and dependency tracking on top.

ElementRef and the DOM

ElementRef wraps a native DOM element in its nativeElement property. You get one from viewChild, or for the component's own host element with inject(ElementRef). It is the escape hatch to the raw DOM, so use it sparingly:

  • Prefer bindings ([class.x], [attr.x], [style.x]) to setting properties by hand.
  • Never build HTML strings and assign them to innerHTML from nativeElement; that bypasses Angular's sanitization (see Security and Accessibility).
  • With server-side rendering, DOM code can run on the server, where it may not exist or behave differently. Keep direct DOM access inside afterNextRender.

Host bindings with the host metadata

Every component and directive has a host element: the element its selector matched. The component can set properties, classes, attributes and listeners on that element from its own class, using the host metadata:

TypeScript
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-toggle',
  template: `<ng-content />`,
  host: {
    role: 'switch',
    tabindex: '0',
    '[class.on]': 'on()',
    '[attr.aria-checked]': 'on()',
    '(click)': 'toggle()',
    '(keydown.space)': 'toggle(); $event.preventDefault()',
  },
})
export class ToggleComponent {
  on = signal(false);

  toggle(): void {
    this.on.update((value) => !value);
  }
}

Plain keys (role, tabindex) are static attributes. Keys in square brackets are bindings, written exactly like in a template: [class.on], [attr.aria-checked], [style.width.px]. Keys in parentheses are listeners, including key filters such as (keydown.space). The expressions run in the component's class, so they can read signals directly.

The decorators @HostBinding('class.on') and @HostListener('click') do the same job on class members. They are still supported, but the host object keeps everything about the host in one place, and it is the style the Angular style guide prefers today.

This stand-in applies a host object to a fake element. Bindings are functions of the component here, because we have no template compiler.

TypeScript Stand-in: applying host metadata to an element

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Here the click listener flips the state, and the bindings are re-evaluated afterward, which is the role change detection plays in Angular.

The same idea on a real element

Here is a browser version with a real button, using plain JavaScript. Click it and watch the class and the aria-pressed attribute change, which is the effect of host bindings on a real host element.

Stand-in: host bindings on a real element

Reusing behavior with hostDirectives

Suppose several components need the same behavior, such as a focus ring or a tooltip. Inheritance is awkward, and repeating the code is worse. Host directives let a component or directive include other directives on its host, without the template author writing anything:

TypeScript
import { Component, Directive, input } from '@angular/core';

@Directive({
  selector: '[appTooltip]',
  host: { '[attr.title]': 'text()' },
})
export class TooltipDirective {
  text = input('', { alias: 'appTooltip' });
}

@Component({
  selector: 'app-icon-button',
  template: `<ng-content />`,
  hostDirectives: [
    {
      directive: TooltipDirective,
      inputs: ['appTooltip: hint'],
    },
  ],
})
export class IconButtonComponent {}
HTML
<app-icon-button hint="Delete item">Trash</app-icon-button>

The rules to remember:

  • The host directive must be standalone.
  • Its inputs and outputs are not exposed automatically. List the ones you want in inputs and outputs, optionally renaming them with 'internal: public'.
  • Angular creates host directives before the component that uses them, and their host bindings and listeners are applied to the same element.

You will meet directives properly in Attribute and Structural Directives, and the compositional style is the main use of hostDirectives.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where can a template reference variable such as #nameInput be used?

    A reference variable is scoped to its template. To get at the element from the class, use viewChild.
  2. 2. What type does viewChild<ElementRef>('box') return?

    The query returns a signal. Its value is undefined until the element exists, and viewChild.required removes the undefined by throwing if it is read too early.
  3. 3. A parent writes <app-tabs><app-tab /><app-tab /></app-tabs>. How does TabsComponent get a list of the app-tab components?

    The tabs were projected in from the parent's template, so they are content, not view. Use a content query.
  4. 4. What does '[class.on]': 'on()' in the host metadata do?

    Host bindings use template syntax but apply to the component's own host element.
  5. 5. Which is required of a directive used in hostDirectives?

    Only standalone directives can be host directives, and only the inputs and outputs you list are exposed.

Summary

  • #name creates a template reference variable that is usable in the same template; on a component tag it is the instance, and #x="exportAs" picks a directive.
  • viewChild, viewChildren, contentChild and contentChildren return signals. .required throws if the result is missing when read, so read it after rendering.
  • View queries search the component's own template; content queries search projected content (direct children by default for contentChildren).
  • ElementRef.nativeElement is an escape hatch. Prefer bindings, and keep raw DOM access in afterNextRender.
  • The host metadata sets static attributes, bindings and listeners on the host element, replacing most @HostBinding and @HostListener uses.
  • hostDirectives composes standalone directives onto a component or directive, exposing only the inputs and outputs you list.

Next: Styling Components and View Encapsulation