Skip to main content

Advanced Topics

Level: Advanced

ℹ️ What You'll Learn
  • View encapsulation
  • Change detection strategies
  • Zone.js and NgZone
  • Web Components
  • Advanced patterns

View Encapsulation

// None - no encapsulation
@Component({
encapsulation: ViewEncapsulation.None
})

// Emulated - default (shadow DOM emulation)
@Component({
encapsulation: ViewEncapsulation.Emulated
})

// ShadowDom - true shadow DOM
@Component({
encapsulation: ViewEncapsulation.ShadowDom
})

Emulated = default. Styles scoped to component.

Change Detection Strategy

// OnPush - only detect changes from inputs/events
@Component({
changeDetection: ChangeDetectionStrategy.OnPush
})
export class OptimizedComponent {
@Input() student!: any;
}

// Default - check every time (slower)
@Component({
changeDetection: ChangeDetectionStrategy.Default
})

OnPush = immutable data = performance.

Zone.js and NgZone

export class PerfComponent {
constructor(private ngZone: NgZone) {}

// Run outside Angular zone (avoid change detection)
heavyComputation() {
this.ngZone.runOutsideAngular(() => {
// Heavy operations here
setInterval(() => {
// Won't trigger change detection
}, 100);
});
}

// Run inside Angular zone
notifyUI() {
this.ngZone.run(() => {
this.studentCount++;
});
}
}

Zone = Angular's change detection. Running outside zone = performance.

View Queries

export class StudentFormComponent implements AfterViewInit {
@ViewChild('studentForm') form!: ElementRef;
@ViewChildren('formInput') inputs!: QueryList<ElementRef>;

ngAfterViewInit() {
console.log('Form:', this.form);
console.log('Inputs count:', this.inputs.length);
}
}

// Template
<form #studentForm>
<input #formInput>
<input #formInput>
</form>

ViewChild = single element. ViewChildren = multiple elements.

Content Projection

// Parent component
<app-card>
<h2>Title</h2>
<p>Content here</p>
</app-card>

// Card component
@Component({
selector: 'app-card',
template: `
<div class="card">
<ng-content></ng-content>
</div>
`
})
export class CardComponent { }

// Named slots
<app-card>
<h2>Title</h2>
<p *ngProjectAs="template">Content</p>
</app-card>

@Component({
template: `
<ng-content select="h2"></ng-content>
<ng-content></ng-content>
`
})

ng-content = project content into component.

Directives Advanced

@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@Input() appHighlight = 'yellow';
@HostListener('mouseenter') onMouseEnter() {
this.el.nativeElement.style.backgroundColor = this.appHighlight;
}
@HostListener('mouseleave') onMouseLeave() {
this.el.nativeElement.style.backgroundColor = '';
}

constructor(private el: ElementRef) {}
}

// Use
<div [appHighlight]="'blue'">Hover me</div>

@HostListener = element events. @HostBinding = element properties.

SMS Advanced Example

// Highly optimized student list
@Component({
selector: 'app-student-list',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class StudentListComponent {
@Input() students!: Student[];
@Output() delete = new EventEmitter<number>();

trackByStudentId(index: number, student: Student) {
return student.id;
}

// Use async to avoid manual subscription
students$ = this.service.getStudents();

constructor(private service: StudentService) {}
}

Key Takeaways

  • ViewEncapsulation = style scoping
  • OnPush = performance optimization
  • Zone = change detection control
  • View queries = access DOM elements
  • Content projection = flexible components
  • Directives = reusable element behavior
💡 Backend Developer Tip

Advanced topics = rarely needed. Master basics first. These patterns solve specific performance/architecture problems.

⚠️ Advanced Pitfalls
  1. Over-optimizing — Premature optimization
  2. Wrong encapsulation — Break style isolation
  3. RunOutsideAngular — Forget to runInside
  4. View queries — Only work after view init
  5. Content projection — Wrong select syntax
🤖Use AI to Learn Faster

Use ChatGPT, Claude, or Copilot to go deeper on Advanced Angular. Try these prompts:

  • "When use ViewEncapsulation.ShadowDom?"
  • "Why run code outside Angular zone?"
  • "How do you project content into components?"
  • "Quiz me on advanced topics"

💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.

nexcoding.in