An Angular component is a class that manages its own template. The class supplies data and logic; the template defines the HTML content and uses bindings to display values or respond to events. Unlike a general-purpose directive, a component is closely tied to the content it produces. Splitting an application into components keeps features manageable, reusable, and easier to test in isolation. section 16.0 section 16.2
To add a component:
- Create a TypeScript class and apply the @Component decorator. Give it a selector and an inline template or a templateUrl for an external HTML file. section 16.2.1 section 5.2.1
- Declare the class in the application’s Angular module, then place an element matching its selector in a template. That element becomes the component’s host. section 16.2.1
- Put display data and logic in the class, and bind to its properties or methods from the template. For example, a count getter can read a model while {{ count }} displays the result. section 9.6.2
Listing 9.23. The contents of the component.ts file in the src/app folder
import { Component } from "@angular/core";
import { Model } from "./repository.model";
@Component({
selector: "app",
templateUrl: "template.html"
})
export class ProductComponent {
private model: Model = new Model();
get count() : number {
return this.model.getProducts().length;
}
}
This complete component pairs a model-backed count getter with a selector and an external template; the matching template displays {{ count }}. section 9.6.2
Every Angular application has a root component for top-level content. Leaving the form, table, layout, and their state in that one component makes the application harder to maintain and test. Separate form and table components can take responsibility for their own content instead. section 16.2 section 16.2.1
Components can coordinate through input and output properties, define CSS styles limited to their templates, and query generated content. They can also receive services: a message component obtains messages from a service and displays the latest one through a computed signal. To test behavior that depends on a host, template, or service, use Angular’s test bed rather than testing the class alone. section 16.5 section 20.3.2 section 29.0









