Components
Components
Section titled “Components”What it means
Section titled “What it means”Components are the fundamental building blocks of Angular applications. Each component controls a portion of the screen (a view) through a TypeScript class that interacts with the view through a template.
Examples
Section titled “Examples”import { Component } from '@angular/core';
@Component({ selector: 'app-root', template: ` <h1>{{ title }}</h1> <p>Welcome, {{ userName }}!</p> <button (click)="handleClick()">Click Me</button> `, styles: [` h1 { color: blue; } `]})export class AppComponent { title = 'My App'; userName = 'Alice';
handleClick() { alert('Button clicked!'); }}
// Separate template file@Component({ selector: 'app-user', templateUrl: './user.component.html', styleUrls: ['./user.component.css']})export class UserComponent { user = { name: 'Bob', age: 30, email: 'bob@example.com' };}Common mistake
Section titled “Common mistake”Forgetting to declare component in module:
// BAD - component created but not declared@Component({...})export class MyComponent {}
// GOOD - add to module declarations@NgModule({ declarations: [MyComponent], imports: [...], bootstrap: [AppComponent]})export class AppModule {}
// In standalone components (Angular 14+)@Component({ selector: 'app-my', standalone: true, imports: [CommonModule], template: `...`})export class MyComponent {}Fix: Either declare in NgModule or use standalone: true.
Quick practice
Section titled “Quick practice”-
What are the three main parts of a component?
Answer
TypeScript class (logic), HTML template (view), and CSS styles (presentation). -
What does the
@Componentdecorator do?Answer
Marks a class as an Angular component and provides metadata (selector, template, styles). -
How do you bind a property to the template?
Answer
Use interpolation: `{{ propertyName }}` or property binding: `[property]="value"`