DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

3

Angular v17.2 Updates - viewChild()

Image description

ViewChild is a way to get a reference on an HTML within the current component’s template.

For instance, if we need our Typescript to access the instance of a given child component, We can use @ViewChild like this:



export class App {
  @ViewChild('list') listComponent!: ListComponent;
  ...
  console.log(this.listComponent.items);
}


Enter fullscreen mode Exit fullscreen mode

The new syntax gives us the same feature as a Signal:



export class App {
  listComponent = viewChild.required<ListComponent>('list');
  ...
  console.log(this.listComponent.items);
}


Enter fullscreen mode Exit fullscreen mode

👉 Differences between these new functions and the old decorators:

These new functions bring a few extra exciting features.

➖ We can eliminate possibly undefined values by making a query required.

➖ Decorator-based queries were satisfied once the component was fully initialized, meaning running side effects required specific lifecycle methods.

➖ With signal-based queries, we receive a signal to rely on computed() or effect() to run such side-effects.

An example is here: Angular viewChild() Demo


I hope you found it useful. Thanks for reading. 🙏

Let's get connected! You can find me on:

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay