Wednesday, May 28, 2025

๐Ÿ”„ How to Extend Component Logic and Template in Angular (Simple Guide) => use of extends and ngTemplateOutlet

When building Angular apps, you might have common logic or reusable layouts across components. Instead of duplicating code, you can use extends in TypeScript and ng-template + ngTemplateOutlet in HTML.

Let’s walk through a simple example with 2 components where one extends logic and also injects custom HTML.


✅ Step 1: Create a Child Component (as base layout)

This is the reusable component that contains a common layout and logic.

child.component.ts

child.component.html

  • ✅ Layout and logic are defined here.
  • ✅ Accepts external HTML through contentTemplate.

✅ Step 2: Create a Parent Component That Extends Child

This component inherits logic from ChildComponent and injects its own template content.

parent.component.ts

parent.component.html

  • ✅ Inherits logic like title and getTitle() from ChildComponent.
  • ✅ Injects its own content via ng-template.

✅ Final Output

  • ChildComponent provides the reusable layout.
  • ParentComponent injects dynamic HTML and extends the logic.
  • This keeps your code DRY, clean, and scalable.

Use Cases: shared card layouts, reusable modal structures, dashboards, etc.

No comments:

Post a Comment

How to Do Cross-Browser Testing on Windows — Including Safari via Playwright

To test follow few steps: Step 1. Install node Step 2. create Folder and run these commands commands Copy Code ...