Sub topic 1
What a Component Is: Decorator, Selector, Template, and Class
Prerequisites
This chapter assumes you know HTML, CSS, ES2015+ JavaScript, basic TypeScript, npm, and how DOM events work. The examples target Angular 19 or later, where components are standalone by default.
Anatomy of a Component
A component is a TypeScript class marked with the @Component decorator. The decorator supplies metadata:
selector: the custom HTML tag that renders the component, such asapp-greeting.template: the HTML the component displays.styles: CSS scoped to this component.
The class holds the state and the methods that the template reads and calls.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-greeting',
template: `
<input [value]="name()" (input)="onInput($event)" />
<p>Hello, {{ name() }}! ({{ name().length }} letters)</p>
<button [disabled]="name() === ''" (click)="name.set('')">Clear</button>
`,
styles: `p { color: steelblue; }`
})
export class GreetingComponent {
name = signal('Ada');
onInput(event: Event) {
this.name.set((event.target as HTMLInputElement).value);
}
}Composing Standalone Components
A standalone component declares its own dependencies. To use another component in a template, list it in the imports array:
import { Component } from '@angular/core';
import { GreetingComponent } from './greeting.component';
@Component({
selector: 'app-root',
imports: [GreetingComponent],
template: `<app-greeting />`
})
export class AppComponent {}If you forget the import, Angular reports an error at build time saying app-greeting is not a known element.
Interpolation and Signals
{{ expression }} renders the result of a template expression as text. Expressions can read class members and do simple operations such as name().length. They cannot contain assignments like = or ++, and they cannot use new.
A signal is a reactive value holder, and you read it by calling it: name(). Writing {{ name }} without the parentheses prints the signal function itself, not its value. A common mistake is leaving off the ().
Property and Event Binding
[property]="expr" sets a DOM property. In the example, [disabled] sets button.disabled to a boolean. Property binding targets DOM properties, not HTML attributes.
(event)="statement" runs a statement when the event fires. $event holds the native event object, so onInput reads event.target.value.
Exercise
A template contains <p>{{ count }}</p>, where count = signal(0). The paragraph shows function text instead of 0. Why, and how do you fix it?
Show answer
Signals are read by calling them. Change the template to {{ count() }}.