Component Basics
Component Basics Interview with follow-up questions
1. What is a component in Angular?
A component is the fundamental building block of an Angular UI. It pairs a TypeScript class (data and logic) with an HTML template (structure) and optional styles, encapsulating one self-contained, reusable piece of the interface. Components compose into a tree to build the whole app.
@Component({
selector: 'app-greeting',
template: `<h1>Hello, {{ name() }}</h1>`,
})
export class GreetingComponent {
name = signal('Ada');
}
Two current points interviewers listen for: components are standalone by default since v17 (they declare their own imports, no NgModule), and component state is increasingly held in signals rather than plain properties so change detection can update only what changed. Also know that a component is essentially "a directive with a template" — which is why it shares lifecycle hooks with directives.
Follow-up 1
How do you create a component in Angular?
To create a component in Angular, you can use the @Component decorator along with a TypeScript class. The @Component decorator is used to define the metadata for the component, such as the selector, template, styles, and more. Here's an example of creating a component:
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: `<h1>Example Component</h1>`,
styles: [`h1 { color: blue; }`]
})
export class ExampleComponent {
// Component logic goes here
}
Follow-up 2
What are the different parts of an Angular component?
An Angular component consists of several parts:
- Selector: It is used to define how the component can be used in the HTML template.
- Template: It defines the HTML structure of the component.
- Styles: It defines the CSS styles for the component.
- Class: It is the TypeScript class that contains the component's logic and data.
- Metadata: It is defined using the
@Componentdecorator and contains additional information about the component, such as inputs, outputs, and lifecycle hooks.
Follow-up 3
Can you explain the lifecycle of an Angular component?
The lifecycle of an Angular component consists of several phases:
- Creation: The component is created by Angular.
- Initialization: The component's properties are initialized.
- Change detection: Angular checks for changes in the component's properties and updates the view if necessary.
- Content projection: If the component has content projection, the projected content is inserted into the component's template.
- Destroy: The component is destroyed and any resources are released.
During each phase, Angular provides lifecycle hooks that allow you to execute custom logic. Some of the commonly used lifecycle hooks are ngOnInit, ngOnChanges, ngDoCheck, ngAfterViewInit, and ngOnDestroy.
2. What is the role of the @Component decorator in Angular?
@Component is a class decorator that marks a class as an Angular component and supplies the metadata Angular needs to create and render it. The key fields:
selector— the CSS selector (e.g.app-user) Angular matches in templates.template/templateUrl— the view's HTML.styles/styleUrls(orstyleUrl) — scoped styles, governed byencapsulation.imports— for standalone components, the other components/directives/pipes this template uses.- Plus options like
changeDetection(e.g.OnPush),providers, andhost.
@Component({
selector: 'app-user',
imports: [CommonModule],
template: `...`,
})
export class UserComponent {}
A modern note worth adding: since v17 components are standalone by default (no standalone: true needed in current versions), so imports lives right here on the decorator rather than in an NgModule.
Follow-up 1
What information does the @Component decorator hold?
The @Component decorator holds metadata that defines various aspects of an Angular component, including its selector, template or templateUrl, styles or styleUrls, inputs, outputs, and providers. It also allows for the configuration of change detection strategy, view encapsulation, and other component-specific settings.
Follow-up 2
How does the @Component decorator relate to the template of an Angular component?
The @Component decorator is used to specify the template or templateUrl of an Angular component. The template defines the structure and layout of the component's view, while the templateUrl allows for the use of an external HTML file as the component's template. The @Component decorator also allows for the configuration of inline styles or external style files using the styles or styleUrls properties.
Follow-up 3
Can you give an example of the usage of the @Component decorator?
Sure! Here's an example of how the @Component decorator can be used:
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: `<h1>Hello, Angular!</h1>`,
styles: [`h1 { color: blue; }`]
})
export class ExampleComponent {
// Component logic goes here
}
3. How do you communicate between components in Angular?
Pick the mechanism based on the component relationship:
- Parent → child: inputs. Pass data down with
@Input()or the modern signal inputinput()(andinput.required()). - Child → parent: outputs. Emit events up with
@Output() x = new EventEmitter()or the modernoutput()function; the parent binds(x)="handle($event)". - Two-way: the
model()signal API enables[(value)]binding for a child that both reads and writes a value. - Unrelated/sibling components: a shared service. Inject a common service and share state through it — ideally a signal (or RxJS
Subject/BehaviorSubject) so consumers react to changes. - Parent reaching into a child:
viewChild()/@ViewChildto call a child's methods or read its state. - App-wide / async data: a store or service exposing signals/observables.
The current framing: prefer the signal-based input(), output(), and model() for new code, and use a signal-backed service for cross-tree communication — it's simpler and works cleanly with zoneless change detection. EventEmitter is still fine for outputs but is really just an event channel, not a general state-sharing tool.
Follow-up 1
What is @Input and @Output in Angular?
@Input and @Output are decorators in Angular that are used for component communication.
@Input decorator is used to pass data from a parent component to a child component. It allows a parent component to bind a value to a property of a child component. The child component can then access and use this value.
@Output decorator is used to emit events from a child component to a parent component. It allows a child component to define custom events and emit them. The parent component can then listen to these events and respond to them.
Follow-up 2
Can you give an example of parent-child communication in Angular?
Sure! Here's an example of parent-child communication in Angular using @Input and @Output decorators:
Parent Component:
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
<h2>Parent Component</h2>
`
})
export class ParentComponent {
}
Child Component:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<h4>Child Component</h4>
<p>{{ message }}</p>
Send Message to Parent
`
})
export class ChildComponent {
@Input() message: string;
@Output() messageSent: EventEmitter = new EventEmitter();
sendMessage() {
this.messageSent.emit('Hello from child');
}
}
In this example, the parent component passes the message 'Hello from parent' to the child component using the @Input decorator. The child component displays this message and also emits a custom event using the @Output decorator when the 'Send Message to Parent' button is clicked. The parent component listens to this event and can respond to it.
Follow-up 3
What is an Event Emitter in Angular?
In Angular, an Event Emitter is a class that allows you to create custom events and emit them from a component. It is used for component communication, specifically for emitting events from a child component to a parent component.
To use an Event Emitter, you need to import it from the '@angular/core' module and create an instance of it in your component. You can then define custom events using the Event Emitter and emit them using the 'emit' method.
Here's an example of using an Event Emitter in Angular:
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-child',
template: `
Send Message
`
})
export class ChildComponent {
@Output() messageSent: EventEmitter = new EventEmitter();
sendMessage() {
this.messageSent.emit('Hello from child');
}
}
In this example, the child component defines a custom event called 'messageSent' using the Event Emitter. When the 'Send Message' button is clicked, the child component emits this event with the message 'Hello from child'. The parent component can listen to this event and respond to it.
4. What is the difference between a component and a directive in Angular?
Both are declared with decorators and share lifecycle hooks, but they differ in one essential way: a component has a template, a directive does not.
- A component (
@Component) controls a region of the UI — it owns a template, styles, and logic, and is rendered where its selector appears. It's the main building block. - A directive (
@Directive) attaches behavior to an existing element without its own view. The two flavors are attribute directives (change appearance/behavior, e.g.ngClass, a custom[tooltip]) and structural directives (change DOM structure, e.g. the legacy*ngIf/*ngFor).
The mental model interviewers like: a component is a directive with a template. That's literally how Angular implements it. A current aside: much of what structural directives did is now handled by the built-in control flow (@if/@for), and components can borrow directive behavior via hostDirectives composition — so you reach for standalone directives mainly to share cross-cutting DOM behavior.
Follow-up 1
Can you give an example where a directive would be more appropriate to use than a component?
Sure! Let's say you have a form in your application and you want to validate the input fields. Instead of creating a separate component for each input field, you can create a directive that handles the validation logic and apply it to the input elements. This way, you can reuse the validation logic across multiple input fields without duplicating code.
Here's an example of a directive that validates an email input field:
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appEmailValidator]'
})
export class EmailValidatorDirective {
constructor(private el: ElementRef) {}
@HostListener('blur')
onBlur() {
const value = this.el.nativeElement.value;
if (!value.includes('@')) {
this.el.nativeElement.classList.add('invalid');
} else {
this.el.nativeElement.classList.remove('invalid');
}
}
}
In this example, the appEmailValidator directive is applied to an input element. When the input field loses focus, the onBlur method is triggered, which checks if the input value contains the '@' symbol. If not, it adds the 'invalid' class to the element.
Follow-up 2
How do you create a directive in Angular?
To create a directive in Angular, you can use the @Directive decorator. Here are the steps:
- Create a new TypeScript file for your directive, e.g.,
my-directive.directive.ts. - Import the necessary dependencies from
@angular/core, such asDirective,ElementRef,HostListener, etc. - Decorate your directive class with the
@Directivedecorator, specifying the selector for your directive. - Implement the logic for your directive inside the class.
Here's an example of a basic directive that changes the background color of an element when clicked:
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef) {}
@HostListener('click')
onClick() {
this.el.nativeElement.style.backgroundColor = 'yellow';
}
}
In this example, the appHighlight directive is applied to an element. When the element is clicked, the onClick method is triggered, which changes the background color of the element to yellow.
Follow-up 3
What are the different types of directives in Angular?
In Angular, there are three types of directives:
Component Directives: These are the most common type of directives in Angular. They are used to create reusable UI components with their own template and logic. Components are declared using the
@Componentdecorator.Attribute Directives: These directives are used to modify the behavior or appearance of an existing element. They are applied using an attribute on the element. Attribute directives are declared using the
@Directivedecorator.Structural Directives: These directives are used to manipulate the structure of the DOM by adding, removing, or manipulating elements. They are applied using a special syntax in the template. Structural directives are declared using the
@Directivedecorator with a*prefix.
Examples of built-in structural directives in Angular are ngIf, ngFor, and ngSwitch.
5. How do you handle data in an Angular component?
Data in a component lives in the class and reaches the template through binding. You hold state as class fields — increasingly as signals — and surface it with interpolation ({{ }}), property binding ([ ]), event binding (( )), and two-way binding ([( )]).
export class CartComponent {
items = signal([]);
total = computed(() => this.items().reduce((s, i) => s + i.price, 0));
add(item: Item) {
this.items.update(list => [...list, item]);
}
}
The modern best-practice answer goes beyond "data binding": prefer signals (signal, computed, linkedSignal) for local/derived state so updates are fine-grained and work with zoneless change detection; fetch and stream server data via services using HttpClient/RxJS (or the new httpResource); and keep templates pure by deriving values with computed() rather than doing work in the template. For shared state across components, hold signals in an injectable service.
Follow-up 1
What is the difference between one-way and two-way data binding?
One-way data binding in Angular is a unidirectional flow of data from the component to the template. It means that changes in the component will be reflected in the template, but changes in the template will not affect the component.
Two-way data binding in Angular is a bidirectional flow of data between the component and the template. It means that changes in the component will be reflected in the template, and changes in the template will also affect the component.
Follow-up 2
How do you implement two-way data binding in Angular?
In Angular, two-way data binding can be implemented using the ngModel directive. The ngModel directive is used to bind the value of an input element to a property in the component. It allows you to both read and write the value of the input element.
Here is an example of how to implement two-way data binding in Angular:
In the above example, the value of the input element is bound to the 'name' property in the component. Any changes in the input element will update the 'name' property, and any changes in the 'name' property will update the input element.
Follow-up 3
What is data binding in Angular?
Data binding in Angular is a mechanism that allows you to synchronize data between the component and the template. It enables you to update the view whenever the data changes, and update the data whenever the user interacts with the view. There are three types of data binding in Angular: one-way binding, two-way binding, and event binding.
6. What are standalone components and why did Angular move to them?
A standalone component declares its own dependencies directly in the @Component decorator's imports array, with no enclosing NgModule. They're the default since Angular 17 (you no longer write standalone: true).
@Component({
selector: 'app-user',
imports: [DatePipe, RouterLink],
template: `...`,
})
export class UserComponent {}
Angular moved to them to eliminate NgModule boilerplate and its confusing indirection: a simpler mental model, easier per-component lazy loading (loadComponent), better tree-shaking, and faster onboarding. Apps bootstrap with bootstrapApplication(AppComponent, { providers: [...] }) and configure features through provider functions (provideRouter, provideHttpClient). Existing NgModule apps interoperate and can migrate incrementally with the official schematic. Interviewers ask this to confirm you build modern Angular rather than NgModule-era apps.
Live mock interview
Mock interview: Component Basics
- Read your scene and goals
- Talk it out; goals tick off live
- Get a score and stronger lines
Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.