Skip to content

Components

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.

app.component.ts
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'
};
}

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.

  1. What are the three main parts of a component?

    AnswerTypeScript class (logic), HTML template (view), and CSS styles (presentation).
  2. What does the @Component decorator do?

    AnswerMarks a class as an Angular component and provides metadata (selector, template, styles).
  3. How do you bind a property to the template?

    AnswerUse interpolation: `{{ propertyName }}` or property binding: `[property]="value"`