Component Fundamentals
Esta página aún no está disponible en tu idioma.
What is a Component?
Section titled “What is a Component?”A component is a self-contained, reusable unit that powers a specific part of your application’s user interface. It elegantly combines a template (HTML for the UI), logic (TypeScript for behavior), and styles (CSS/SCSS for visuals) into a cohesive module. Components are the cornerstone of Angular’s modular architecture, enabling you to build scalable, maintainable apps.
In Angular 18+, all components are standalone by default — the standalone: true flag is no longer needed in the @Component decorator.
Anatomy of a Component
Section titled “Anatomy of a Component”A component is composed of four essential parts:
- Decorator — The
@Componentdecorator flags a class as a component, providing Angular with instructions on how to process it. - Metadata — Properties like
selector,template, andstylesdefine the component’s structure, behavior, and appearance. - Template — The HTML that renders the UI, either inline or in a separate
.htmlfile. - Styles — The CSS or SCSS that styles the component, either inline or in a separate file.
import { Component, signal, ChangeDetectionStrategy } from '@angular/core';
@Component({ selector: 'app-greeting', standalone: true, changeDetection: ChangeDetectionStrategy.OnPush, template: `<h2>Hello, {{ name() }}!</h2>`, styles: [`h2 { color: teal; }`]})export class GreetingComponent { name = signal('Angular');}In Angular 18,
standalone: truemust be explicitly declared. From Angular 19+, it becomes the default and can be omitted. In both cases, the component directly manages its ownimportsfor any dependencies it uses (pipes, directives, other components).
Creating a Component
Section titled “Creating a Component”Using the Angular CLI
Section titled “Using the Angular CLI”The Angular CLI generates all necessary files and boilerplate:
ng generate component user-card# Or shorthand:ng g c user-cardThis creates a folder with:
user-card.component.ts— Component logic and metadatauser-card.component.html— Templateuser-card.component.scss— Stylesuser-card.component.spec.ts— Unit tests
In Angular 18+, the CLI generates standalone components by default. No module declaration is required.
Generated Component (Angular 18+)
Section titled “Generated Component (Angular 18+)”import { Component, ChangeDetectionStrategy } from '@angular/core';
@Component({ selector: 'app-user-card', standalone: true, templateUrl: './user-card.component.html', styleUrl: './user-card.component.scss', changeDetection: ChangeDetectionStrategy.OnPush, imports: []})export class UserCardComponent {}Key differences from legacy (pre-Angular 14):
standalone: truemarks the component as self-contained (explicit in Angular 18, implicit from Angular 19+).- No NgModule declaration needed — the component manages its own dependencies.
importsarray lives in the component itself — not in a module.styleUrl(singular) replaces the oldstyleUrls(array) for single stylesheet.ChangeDetectionStrategy.OnPushis the recommended default for all components.
Useful CLI Flags
Section titled “Useful CLI Flags”# Generate with inline template and stylesng g c user-card --inline-template --inline-style
# Generate inside a specific folderng g c features/dashboard/widgets/stats-card
# Generate without test fileng g c user-card --skip-tests
# Generate with a specific prefixng g c user-card --prefix=uiSelectors
Section titled “Selectors”The selector property defines the custom HTML tag for your component:
import { Component, ChangeDetectionStrategy } from '@angular/core';
@Component({ selector: 'app-user-card', standalone: true, changeDetection: ChangeDetectionStrategy.OnPush, template: `<p>User Card works!</p>`})export class UserCardComponent {}Best practices for selectors:
- Use a consistent prefix (e.g.,
app-,ui-,shared-) to avoid conflicts with native HTML elements. - Use kebab-case (e.g.,
app-user-card). - Tag selectors are the most common pattern.
Attribute and class selectors are also possible for specific use cases:
// Attribute selectorselector: '[appHighlight]'
// Class selector (rare)selector: '.app-tooltip'Styling Components
Section titled “Styling Components”Style Encapsulation
Section titled “Style Encapsulation”Angular scopes styles to the component by default using ViewEncapsulation.Emulated:
import { Component, ChangeDetectionStrategy, ViewEncapsulation } from '@angular/core';
@Component({ selector: 'app-card', standalone: true, changeDetection: ChangeDetectionStrategy.OnPush, template: `<div class="card">Content</div>`, styles: [`.card { border: 1px solid #ccc; padding: 16px; }`], encapsulation: ViewEncapsulation.Emulated // default})export class CardComponent {}Encapsulation options:
| Mode | Behavior |
|---|---|
Emulated (default) | Scopes styles with unique attributes — styles don’t leak out. |
ShadowDom | Uses native Shadow DOM for strict browser-level isolation. |
None | No encapsulation — styles become global. Use with caution. |
External vs Inline Styles
Section titled “External vs Inline Styles”@Component({ selector: 'app-card', standalone: true, changeDetection: ChangeDetectionStrategy.OnPush, templateUrl: './card.component.html', styleUrl: './card.component.scss'})export class CardComponent {}
@Component({ selector: 'app-badge', standalone: true, changeDetection: ChangeDetectionStrategy.OnPush, template: `<span class="badge">{{ label() }}</span>`, styles: [`.badge { padding: 4px 8px; border-radius: 4px; }`]})export class BadgeComponent { label = input.required<string>();}Note:
styleUrl(singular) was introduced in Angular 17. The legacystyleUrls: [...](array) is still supported but no longer generated by the CLI.