Coding exercise: build a reusable modal component in Angular.

Angular practical coding · Freshers and experienced

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

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