Angular Query Signals - Exploring How To Use Them
Today we're going to explore a feature of the Angular framework called Angular Query Signals.
Angular keeps evolving with the new Angular signals feature.
And one useful place to use a signal is when querying (or also finding) child elements in a components template.
But wait. Remember how we used to do things as web devs? 😄 😄 😄
Back in the good-ole days when we used jQuery we would query an element like this.
let tag = $( "#myId" );
With Angular query signals we do something similar.
Except, it looks different because we now build awesome apps with the modern Angular framework.
A query signal looks like this. It's quite simple to understand.
import { Component, ElementRef, viewChild } from "@angular/core";
@Component({
selector: 'app-root',
standalone: true,
template: `
<h1 #tag></h1>
`
})
export class AppComponent {
headline = viewChild<ElementRef>('tag');
}
The query here is viewChild
which queries the components template for the tag
element.
And now we can work with this query signal by calling it as a function.
import { Component, ElementRef, OnInit, viewChild } from "@angular/core";
@Component({
selector: 'app-root',
standalone: true,
template: `
<h1 #tag></h1>
`
})
export class AppComponent implements OnInit {
headline = viewChild<ElementRef>('tag');
ngOnInit() {
const value = this.headline();
console.log(value);
}
}
And if we take a look at the console we'll see an ElementRef
.
So why would we do this?
The query signals eliminate the need for AfterContentInit
and AfterViewInit
hooks because we can use computed or effect as we do with any signal.
We can also make the view child to be required with the required function.
import { Component, ElementRef, viewChild } from "@angular/core";
@Component({
selector: 'app-root',
standalone: true,
template: `
<h1 #tag></h1>
`
})
export class AppComponent {
headline = viewChild.required<ElementRef>('tag');
}
If the tag
element is missing the required function with throw an error letting us know that the element we expected doesn't exist.
So if we expect a child element that doesn't exist like this.
import { Component, ElementRef, OnInit, viewChild } from "@angular/core";
@Component({
selector: 'app-root',
standalone: true,
template: `
<h1 #hidden></h1>
`
})
export class AppComponent implements OnInit{
headline = viewChild.required<ElementRef>('tag');
ngOnInit(): void {
console.log(this.headline());
}
}
We'll get an error in the console.
And that my friend is how to start using the Angular query signals. They'll help you avoid the need for the AfterContentInit
and other hooks.
Have a great Angular time.
Daniel Kreider