Learn Angular · 11/14

Advanced Component Techniques

8 min read

👋 Welcome, Developer

We have arrived at Topic 11. You have mastered the basics of binding, structural directives, and basic routing. Now, the training wheels are off.

We are entering the territory of "Professional Angular Development." This is where we stop writing components that simply exist and start writing components that perform, scale, and adapt.

Interesting Fact: Did you know that the "Angular" name comes from the angle brackets < > used in HTML? While this seems obvious, many developers assume it implies the "angular" (sharp/complex) nature of the learning curve. We assure you, the curve is merely a hill, and we are climbing it together. 🏔️

This guide covers four critical pillars of advanced component architecture. We will define the problem, present the solution, and implement it with strict adherence to industry standards.


1. Content Projection: Building Reusable Wrappers with ng-content

The Definition

Content Projection is a pattern where you insert, or "project," HTML content from a parent component into a designated slot within a child component.

The Problem

Imagine you are building a CardComponent.
In a basic approach, you might use @Input() strings for the title and body.

typescript
// Rigid Approach
@Input() title: string = '';
@Input() body: string = '';

But what if you want the "body" to contain a button? Or an image? Or another component? You cannot pass complex HTML structures easily through string inputs. You would end up with a mess of *ngIf statements inside the card to handle every possible content type.

The Solution: <ng-content>

Angular allows you to create a "slot" in the child component's template where the parent's HTML will land. This is similar to the standard HTML <slot> element but designed for Angular's lifecycle.

Implementation

A. Single Slot Projection

This projects everything placed between the component tags.

Child Component (card.component.ts):

html
<div class="card-shadow">
  <div class="card-header">
    My Card
  </div>
  <div class="card-body">
    <!-- The content goes here -->
    <ng-content></ng-content>
  </div>
</div>

Parent Component Usage:

html
<app-card>
  <p>I am a paragraph projected into the card!</p>
  <button>I am a button!</button>
</app-card>

B. Multi-Slot Projection (Select Attribute)

Often, you need to project content into specific areas (e.g., a header and a footer). We use the select attribute, which acts like a CSS selector.

Child Component (card.component.ts):

html
<div class="card">
  <div class="header">
    <!-- Only content with the 'card-header' attribute goes here -->
    <ng-content select="[card-header]"></ng-content>
  </div>
  
  <div class="body">
    <!-- Catch-all for everything else -->
    <ng-content></ng-content>
  </div>
  
  <div class="footer">
    <!-- Only content with the 'card-footer' attribute goes here -->
    <ng-content select="[card-footer]"></ng-content>
  </div>
</div>

Parent Component Usage:

html
<app-card>
  <!-- Order does not matter here; the selector finds the right slot -->
  <h3 card-header>User Profile</h3>
  
  <p>This is the main body content.</p>
  
  <button card-footer>Save Changes</button>
</app-card>

Note: The select attribute supports tags (select="h1"), classes (select=".title"), and attributes (select="[card-header]"). Attributes are preferred in industry practice as they don't interfere with CSS styling.


2. DOM Access: Using ViewChild and ViewChildren

The Definition

@ViewChild and @ViewChildren are property decorators that allow a component to query its own template (view) to get references to DOM elements or child component instances.

The Problem

Angular uses declarative data binding ([value]="prop"). However, sometimes you need imperative access.

  • Example 1: You need to focus an input field as soon as a modal opens. You cannot "bind" focus; you must call .focus() on the DOM element.
  • Example 2: You need to trigger a method reset() inside a child component from the parent.

The Solution

We use queries to capture these references.

Implementation

A. Accessing a Child Component

Child (CounterComponent):

typescript
@Component({ ... })
export class CounterComponent {
  count = 0;
  reset() { this.count = 0; }
}

Parent:

typescript
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { CounterComponent } from './counter.component';

@Component({ ... })
export class ParentComponent implements AfterViewInit {
  // Query for the component type
  @ViewChild(CounterComponent) childCounter!: CounterComponent;

  ngAfterViewInit() {
    // Available only after the view initializes
    console.log(this.childCounter.count); 
  }

  resetChild() {
    this.childCounter.reset();
  }
}

B. Accessing a Native DOM Element

To find a standard HTML element, we mark it with a Template Reference Variable (#variableName).

Template:

html
<input #myInput type="text" placeholder="Focus me...">
<button (click)="focusInput()">Focus</button>

Component:

typescript
import { Component, ViewChild, ElementRef } from '@angular/core';

@Component({ ... })
export class FocusComponent {
  // We look for the reference string 'myInput'
  // We read it as an ElementRef to access the native DOM
  @ViewChild('myInput', { static: false }) inputRef!: ElementRef;

  focusInput() {
    // NATIVE ELEMENT ACCESS
    // Warning: Direct DOM manipulation should be minimized.
    this.inputRef.nativeElement.focus();
  }
}

Crucial Concept: { static: true } vs { static: false }.

  • true: The query result is available in ngOnInit. Use this only if the element is always present and not wrapped in an *ngIf.
  • false (Default): The query result is available in ngAfterViewInit. This is safer for elements that might be dynamic.

3. Dynamic Components: Rendering Programmatically

The Definition

Dynamic Component Loading is the process of creating and rendering a component at runtime without defining it in the component's HTML template explicitly.

The Problem

You are building a Dashboard. The user can add widgets. One user wants a "Weather Widget," another wants a "Stock Widget," and a third wants a "Calendar."
If you use *ngIf, you load the code for all widgets even if they aren't used, and your template becomes unreadable:

html
<!-- The Anti-Pattern -->
<app-weather *ngIf="type === 'weather'"></app-weather>
<app-stocks *ngIf="type === 'stocks'"></app-stocks>
<app-calendar *ngIf="type === 'calendar'"></app-calendar>
<!-- Imagine 50 more of these -->

The Solution

Use ViewContainerRef to treat a DOM element as a container where we can insert components via TypeScript code.

Implementation (Modern Angular 13+)

1. Create an anchor directive (Optional but recommended)
This helper tells Angular where to place the dynamic component.

typescript
@Directive({ selector: '[appAdHost]' })
export class AdHostDirective {
  constructor(public viewContainerRef: ViewContainerRef) { }
}

2. The Host Component

typescript
import { Component, ViewChild, OnInit } from '@angular/core';
import { AdHostDirective } from './ad-host.directive';
import { WeatherComponent } from './weather.component';

@Component({
  template: `
    <h3>Dynamic Board</h3>
    <ng-template appAdHost></ng-template>
  `
})
export class DashboardComponent implements OnInit {
  @ViewChild(AdHostDirective, { static: true }) adHost!: AdHostDirective;

  ngOnInit() {
    this.loadComponent();
  }

  loadComponent() {
    const viewContainerRef = this.adHost.viewContainerRef;
    viewContainerRef.clear(); // Clear previous components

    // Create the component
    const componentRef = viewContainerRef.createComponent(WeatherComponent);
    
    // Pass data to the new component
    componentRef.instance.city = 'Kathmandu';
  }
}

Industry Standard: This approach is cleaner than *ngIf soup. It allows for "Lazy Loading" of components if combined with imports properly, significantly reducing the initial bundle size.


4. Performance Boost: OnPush Change Detection

The Definition

Change Detection is the internal mechanism Angular uses to see if data has changed and the DOM needs updating.

The Problem

By default, Angular uses the Default strategy. This is a "better safe than sorry" approach.
Every time any event happens (click, timer, HTTP request) anywhere in the app, Angular checks every single component in the tree to see if it changed.
In a large app with 100 components, one click might trigger 100 checks. This burns CPU cycles. 📉

The Solution: OnPush

ChangeDetectionStrategy.OnPush tells Angular: "Ignore this component (and its children) unless specific conditions are met."

The component will only update if:

  1. The Input reference changes (Concept of Immutability).
  2. An event originated from inside this specific component (e.g., a button click in this template).
  3. We manually tell it to check (markForCheck).
  4. An AsyncPipe in the template emits a new value.

Implementation

typescript
import { Component, ChangeDetectionStrategy, Input } from '@angular/core';

@Component({
  selector: 'app-user-profile',
  template: `
    <p>User: {{ user.name }}</p>
    <p>Score: {{ user.score }}</p>
  `,
  // The Magic Line
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class UserProfileComponent {
  @Input() user!: { name: string, score: number };
}

The Immutability Caveat

With OnPush, mutating data does not trigger an update.

Bad Practice (Will NOT update UI in OnPush):

typescript
updateScore() {
  // We are mutating the existing object. 
  // The memory address (reference) of 'user' did not change.
  this.user.score = 99; 
}

Good Practice (Will update UI):

typescript
updateScore() {
  // We create a NEW object with the new data.
  // The reference changes, Angular detects this.
  this.user = { ...this.user, score: 99 };
}

Imagination Time: Think of the Default strategy as a security guard checking every single ID card in a stadium every 5 seconds. Think of OnPush as a guard who sleeps until a specific turnstile beeps. The second guard is much more efficient. 😴👮


🏁 Conclusion

You have graduated from simple layouts to advanced architecture.

  1. Content Projection lets you create flexible containers.
  2. ViewChild gives you surgical precision over the DOM.
  3. Dynamic Components allow your app to shape-shift at runtime.
  4. OnPush makes your application fly.

Practice these. Do not just read them. Create a component, break it, and fix it using these techniques.

📚 References & Further Reading

Challenge

Your task is to build a highly performant and reusable WidgetHostComponent in Angular. This component must be capable of dynamically rendering different child components (WeatherWidgetComponent or NewsWidgetComponent) into a specific slot while accepting a separate header and footer via content projection.

Requirements:

  1. WidgetHostComponent Configuration:

    • Set the component's change detection strategy to OnPush for optimal performance.
    • The component must accept a string @Input() named widgetType which can be either 'weather' or 'news'.
  2. WidgetHostComponent Template:

    • Implement a multi-slot content projection layout.
    • Define a slot that accepts content projected with a [widget-header] attribute.
    • Define another slot that accepts content projected with a [widget-footer] attribute.
    • Create an ng-template element between the header and footer slots. This template will serve as the anchor point for dynamic components. Assign it a template reference variable named widgetContentHost.
  3. Dynamic Loading Logic in WidgetHostComponent:

    • Use the @ViewChild decorator to get a ViewContainerRef for the widgetContentHost anchor.
    • Implement the ngOnChanges lifecycle hook to react to changes in the widgetType input.
    • Inside ngOnChanges, your logic must first clear the ViewContainerRef. Then, based on the value of widgetType, use ViewContainerRef.createComponent() to dynamically instantiate and insert either the WeatherWidgetComponent or the NewsWidgetComponent.
  4. AppComponent Implementation:

    • In the AppComponent template, use your <app-widget-host>.
    • Create two buttons, "Load Weather" and "Load News". Clicking these buttons should update a property in the AppComponent that is bound to the widgetType input of the WidgetHostComponent.
    • Project an <h2> element into the [widget-header] slot.
    • Project a <small> element into the [widget-footer] slot.

Expected result

The final rendered UI should present a main title "Dynamic Widget Dashboard". Below the title, there must be two buttons, "Load Weather" and "Load News".

Below the buttons, the WidgetHostComponent should render a structured block containing three parts:

  1. An <h2> header, projected from the AppComponent.
  2. A content area that dynamically displays the content of either the weather or news widget, depending on which button was last clicked.
  3. A <small> footer, also projected from the AppComponent.

For example, after clicking the "Load Weather" button, the block should display the header, followed by "Weather Widget Content: Sunny, 25°C", and then the footer. Clicking the "Load News" button must replace only the weather content with "News Widget Content: Major Tech Announcement!" while the projected header and footer remain unchanged.

typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.