Coding exercise: build a reusable modal component in Angular.
Model answer
Make a standalone component that gets its title and open state from inputs, emits a close event, and projects its body with ng-content so any content can go inside. Close on Escape and on the backdrop click.
@Component({
selector: 'app-modal',
host: { '(document:keydown.escape)': 'closed.emit()' },
template: `
@if (open()) {
<div class="backdrop" (click)="closed.emit()">
<div class="box" role="dialog" aria-modal="true" [attr.aria-label]="title()" (click)="$event.stopPropagation()">
<h2>{{ title() }}</h2>
<ng-content />
<button (click)="closed.emit()">Close</button>
</div>
</div>
}`,
})
export class Modal {
open = input(false);
title = input('');
closed = output<void>();
}
// Use it
// <app-modal [open]="show()" title="Delete item?" (closed)="show.set(false)">
// <p>This cannot be undone.</p>
// </app-modal>For a complete answer, add focus handling (the Angular CDK Dialog does focus trapping for you) and stop the page behind from scrolling.
Tips
- The CDK Dialog is a good production answer; the hand-built one shows you understand the pieces.
Practise it yourself in the React and Angular code playground.
Learn this topic
Angular Tutorial: Beginner to Advanced .
Sign in to add your own answer.
More questions
- Coding exercise: build a Todo application in Angular.
- Coding exercise: create a search box with debounce in Angular.
- Coding exercise: fetch API data and display it in a table in Angular.
- Coding exercise: implement pagination in Angular.
- Coding exercise: create a login form with validation in Angular.
- Coding exercise: build a parent-child communication example in Angular.