Angular Tutorial 0/55 lessons ~6 min read Lesson 40

    Angular Signal Queries

    Signal-based queries — viewChild, viewChildren, contentChild, contentChildren — replace many decorator query patterns.

    Course progress0%
    Focus
    7 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Signal-based queries — viewChild, viewChildren, contentChild, contentChildren — replace many decorator query patterns. Results are signals, so they work cleanly with computed and effects after the view initializes.

    Purpose of this lesson

    You will query a child component or element as a signal and react when it becomes available.

    Understanding the topic

    Query kinds:

    • viewChild / viewChildren — children in this component's template.
    • contentChild / contentChildren — projected content (ng-content).
    • Queries may be undefined until after view init — use computed or effects that tolerate that.
    • Prefer signal queries over @ViewChild in new code.

    Informative example

    Focus an input after render:

    typescript
    import { Component, effect, ElementRef, viewChild } from "@angular/core";
    @Component({
    selector: "tlp-search",
    template: `<input #box type="search" [placeholder]="placeholder" />`,
    })
    export class SearchComponent {
    placeholder = "Search courses";
    box = viewChild.required<ElementRef<HTMLInputElement>>("box");
    constructor() {
    effect(() => {
    this.box().nativeElement.focus();
    });
    }
    }

    Best practices

    • Use viewChild.required only when the template always contains the target.
    • Avoid reading queries in the constructor body before the view exists — use an effect or afterNextRender.

    Common mistakes

    • Assuming a query is defined during construction.
    • Querying by string template ref that was renamed in the template.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    1 questions
    1IntermediateQuestionWhen do signal queries get their value?+

    Answer

    After Angular creates the view (and content for content queries). Until then optional queries are undefined; required queries throw if missing when first read after init expectations.
    Ready to mark this lesson complete?Track your journey across the entire course.