DEV Community

Dhivya Delphina
Dhivya Delphina

Posted on

Angular Concepts Overview

βœ… 1. What is Angular, and why does Angular use TypeScript?

πŸ”Ή Angular:

Angular is a TypeScript-based open-source front-end framework developed by Google for building dynamic web applications. It follows component-based architecture and comes with a powerful set of features like:

  • Two-way data binding
  • Dependency Injection
  • RxJS support
  • Routing
  • Form validation
  • Modular development

πŸ”Ή Why TypeScript?

TypeScript is a superset of JavaScript that adds static typing and OOP features like classes, interfaces, and access modifiers.

🧠 Key Reasons Angular uses TypeScript:

  • Type Safety: Helps catch errors during development.
  • Tooling Support: Better autocompletion and refactoring with IDEs.
  • OOP Support: Facilitates modular architecture with interfaces and decorators.
  • Advanced Features: Decorators (@Component, @Injectable) are native to TypeScript.

βœ… Real-world analogy:

Using TypeScript in Angular is like driving a car with ABS and sensors β€” it keeps you safe by warning about issues before they become real problems in production.


βœ… 2. What is Angular Material?

Angular Material is a UI component library developed by Angular team following the Material Design principles by Google.

πŸ”Ή Features:

  • Pre-built UI components (buttons, dialogs, date pickers, tabs)
  • Responsive layout using Flex Layout
  • Accessible and mobile-friendly
  • Customizable themes

πŸ”Ή Example:

ng add @angular/material
Enter fullscreen mode Exit fullscreen mode
<mat-toolbar color="primary">My App</mat-toolbar>
<mat-card>
  <mat-card-title>Welcome</mat-card-title>
</mat-card>
Enter fullscreen mode Exit fullscreen mode

βœ… Scenario:

Use Angular Material when you want to build a consistent UI quickly without reinventing the wheel. Ideal for dashboards, admin panels, or enterprise apps.


βœ… 3. What is a directive, and what are the types of directives?

πŸ”Ή A directive in Angular is a class with a @Directive decorator that lets you manipulate the DOM or component behavior.

πŸ”Έ Types of Directives:

  1. Component Directive – Technically a directive with a template.
    • e.g., @Component
  2. Structural Directive – Changes the DOM structure
    • e.g., *ngIf, *ngFor, *ngSwitch
  3. Attribute Directive – Alters the appearance or behavior of an element.
    • e.g., ngClass, ngStyle, or custom ones

πŸ”Ή Example: Custom Attribute Directive

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor(el: ElementRef) {
    el.nativeElement.style.backgroundColor = 'yellow';
  }
}
Enter fullscreen mode Exit fullscreen mode
<p appHighlight>This text is highlighted.</p>
Enter fullscreen mode Exit fullscreen mode

βœ… 4. What are the building blocks of Angular?

  1. Modules (NgModules) – Group related features
  2. Components – UI + logic (template + TS class)
  3. Templates – HTML with Angular syntax
  4. Directives – Modify DOM or behavior
  5. Services – Business logic, data access, reusable code
  6. Routing – Navigation and views
  7. Pipes – Transform data in templates
  8. Dependency Injection (DI) – Service injection

βœ… 5. What is Dependency Injection (DI)?

DI is a design pattern where dependencies (services, config, etc.) are injected into components instead of hard-coding them.

πŸ”Ή Benefits:

  • Loose coupling
  • Easier testing
  • Better reusability

πŸ”Ή Example:

@Injectable({ providedIn: 'root' })
export class LoggerService {
  log(msg: string) {
    console.log(msg);
  }
}

@Component({ ... })
export class HomeComponent {
  constructor(private logger: LoggerService) {
    this.logger.log('Home loaded');
  }
}
Enter fullscreen mode Exit fullscreen mode

βœ… Real-world analogy:

It’s like ordering a pizza instead of baking one yourself β€” let someone else handle it and just enjoy the result.


βœ… 6. What is Data Binding, and how many ways can it be implemented?

Data binding connects component logic with the UI.

πŸ”Ή 1. Interpolation ({{ }})

Displays dynamic data.

<p>Hello, {{ name }}</p>
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή 2. Property Binding ([property])

Binds component data to HTML property.

<img [src]="imgUrl">
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή 3. Event Binding ((event))

Handles user events like clicks.

<button (click)="onClick()">Click Me</button>
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή 4. Two-way Binding ([(ngModel)])

Syncs data both ways.

<input [(ngModel)]="username">
Enter fullscreen mode Exit fullscreen mode

βœ… 7. What are filters in Angular?

In Angular, Pipes are the equivalent of filters (from AngularJS).

πŸ”Ή Built-in Pipes:

  • date, uppercase, lowercase, currency, percent, etc.

πŸ”Ή Custom Pipe Example:

@Pipe({ name: 'reverse' })
export class ReversePipe implements PipeTransform {
  transform(value: string): string {
    return value.split('').reverse().join('');
  }
}
Enter fullscreen mode Exit fullscreen mode

Usage:

{{ 'hello' | reverse }} <!-- Output: olleh -->
Enter fullscreen mode Exit fullscreen mode

βœ… 8. What is ViewEncapsulation?

Controls how CSS styles are scoped to a component.

πŸ”Έ Types:

  1. Emulated (default): Styles scoped via unique attributes
  2. None: Styles are global
  3. ShadowDom: Uses native Shadow DOM

βœ… Example:

@Component({
  ...
  encapsulation: ViewEncapsulation.Emulated // or None / ShadowDom
})
Enter fullscreen mode Exit fullscreen mode

βœ… 9. Why prioritize TypeScript over JavaScript in Angular?

πŸ”Ή Reasons:

  • Static typing β†’ Fewer runtime errors
  • Decorators β†’ Metadata and Dependency Injection
  • Better tooling β†’ IntelliSense, refactoring
  • Interfaces, enums, access modifiers
  • Ahead-of-time (AOT) compatibility

Angular is written in TypeScript, making it a natural fit.


βœ… 10. What do you understand by RouterOutlet and RouterLink?

πŸ”Έ RouterOutlet

A directive that marks where the routed component should be displayed.

<router-outlet></router-outlet>
Enter fullscreen mode Exit fullscreen mode

πŸ”Έ RouterLink

Binds to route paths in your templates.

<a routerLink="/home">Go to Home</a>
Enter fullscreen mode Exit fullscreen mode

βœ… 11. What happens when you use the <script> tag within a template?

Using <script> tags inside Angular templates is strongly discouraged and generally not supported.

πŸ”₯ Why it's a problem:

  • Security Risk: Angular sanitizes templates to prevent XSS attacks.
  • Ignored Content: Angular will ignore or strip out <script> tags in the DOM.
  • Best Practice Violation: Script logic should go in the component .ts file, not in the template.

🧠 Instead of this:

<!-- ❌ Not recommended -->
<script>alert('Hi')</script>
Enter fullscreen mode Exit fullscreen mode

βœ… Do this:

ngOnInit() {
  alert('Hi');
}
Enter fullscreen mode Exit fullscreen mode

βœ… 12. What is ViewChild, and when would you use { static: false }?

πŸ”Ή @ViewChild

It allows access to a DOM element, directive, or component inside your template from your component class.

Syntax:

@ViewChild('myElement', { static: false }) myEl: ElementRef;
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή static: false

Use when the element is inside an *ngIf, *ngFor, or any structural directive and you want to access it after the view initializes (ngAfterViewInit).

πŸ”Ή static: true

Use when the element is always present and you want to access it in ngOnInit.

βœ… Example:

<div *ngIf="show" #myDiv>Hello</div>
Enter fullscreen mode Exit fullscreen mode
@ViewChild('myDiv', { static: false }) myDiv: ElementRef;
Enter fullscreen mode Exit fullscreen mode

βœ… 13. How many ways can we share data between components?

πŸ”Έ 1. @Input() / @Output()

  • Parent β†’ Child: @Input()
  • Child β†’ Parent: @Output() with EventEmitter

πŸ”Έ 2. Shared Service with BehaviorSubject or Subject

Best for unrelated components (e.g., sibling to sibling).

πŸ”Έ 3. Router State / Route Params

Pass data during routing.

πŸ”Έ 4. ngRx / State Management

Advanced: used in large-scale apps.

βœ… Example:

// service.ts
data$ = new BehaviorSubject<string>('initial');

// component A
this.service.data$.next('new value');

// component B
this.service.data$.subscribe(value => this.received = value);
Enter fullscreen mode Exit fullscreen mode

βœ… 14. Angular Lifecycle Hooks

These are methods that allow you to tap into different phases of a component's lifecycle.

Hook When it’s called
ngOnChanges() When an input-bound property changes
ngOnInit() After component initialization
ngDoCheck() Custom change detection
ngAfterContentInit() After <ng-content> is projected
ngAfterContentChecked() After content is checked
ngAfterViewInit() After component’s view is initialized
ngAfterViewChecked() After the view and child views are checked
ngOnDestroy() Just before component is destroyed

βœ… Example:

ngOnInit() {
  console.log("Component initialized");
}
Enter fullscreen mode Exit fullscreen mode

βœ… 15. What is AOT compilation? What are the advantages of AOT?

πŸ”Ή AOT (Ahead-of-Time Compilation)

Angular compiles HTML and TypeScript into JavaScript at build time, rather than in the browser.

πŸ”Έ Advantages:

  • Faster Rendering: Templates are pre-compiled.
  • Smaller Bundle Size
  • Early Error Detection
  • Security: Template injection attacks are minimized.

βœ… Usage:

AOT is enabled by default in production:

ng build --prod
Enter fullscreen mode Exit fullscreen mode

βœ… 16. What is "sourceMap": true in Angular?

In angular.json, this config generates source maps that map minified code back to the original TypeScript code.

βœ… Why it’s useful:

  • Enables debugging in the browser (e.g., Chrome DevTools)
  • Maps back errors to actual .ts files instead of .js

βœ… 17. What is RxJS?

RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using Observables.

πŸ”Ή Core Concepts:

  • Observable: Represents a stream of data.
  • Observer: Consumes the data.
  • Operators: Transform data (e.g., map, filter, mergeMap)

βœ… Example:

interval(1000).pipe(
  map(x => x * 2)
).subscribe(console.log);
Enter fullscreen mode Exit fullscreen mode

βœ… 18. Promise vs Observable

Feature Promise Observable
Eager vs Lazy Eager Lazy
Values One Multiple
Cancelable ❌ βœ…
Operators ❌ βœ…
Async Operations βœ… βœ…

βœ… Example:

// Promise
fetchData().then(res => ...);

// Observable
this.service.getData().subscribe(res => ...);
Enter fullscreen mode Exit fullscreen mode

βœ… 19. What are Template and Reactive Forms?

πŸ”Ή Template-driven Forms

  • Use ngModel
  • Simpler, best for basic forms
  • Defined in HTML

πŸ”Ή Reactive Forms

  • Use FormGroup, FormControl, FormBuilder
  • More robust and testable
  • Defined in TypeScript

βœ… Example:

this.form = new FormGroup({
  name: new FormControl('')
});
Enter fullscreen mode Exit fullscreen mode

βœ… 20. What are forRoot() and forChild() in Angular?

πŸ”Ή forRoot()

Used in root module to configure global providers or singletons.

πŸ”Ή forChild()

Used in feature modules to prevent re-instantiating services.

βœ… Example:

RouterModule.forRoot(routes) // AppModule
RouterModule.forChild(childRoutes) // FeatureModule
Enter fullscreen mode Exit fullscreen mode

βœ… 21. How to handle multiple HTTP requests in Angular?

Use RxJS operators like forkJoin, combineLatest, zip, or merge.

βœ… forkJoin Example:

forkJoin([
  this.service.getUser(),
  this.service.getOrders()
]).subscribe(([user, orders]) => {
  console.log(user, orders);
});
Enter fullscreen mode Exit fullscreen mode
  • forkJoin waits for all Observables to complete.

βœ… 22. Map vs mergeMap vs switchMap vs concatMap

Operator Behavior
map Transforms values
mergeMap Flattens & merges inner Observables concurrently
switchMap Cancels previous, switches to new Observable
concatMap Runs requests sequentially

βœ… Example:

search$.pipe(
  debounceTime(300),
  switchMap(term => this.api.search(term))
)
Enter fullscreen mode Exit fullscreen mode

switchMap is great for search/autocomplete where you want the latest request only.


βœ… 23. What are class decorators?

Class decorators add metadata or modify behavior of classes.

βœ… Common Angular Class Decorators:

  • @Component
  • @Injectable
  • @Directive
  • @NgModule

Example:

@Injectable({ providedIn: 'root' })
export class MyService {}
Enter fullscreen mode Exit fullscreen mode

βœ… 24. What is the @Component Decorator in Angular?

Used to define a component and its metadata.

βœ… Example:

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent {}
Enter fullscreen mode Exit fullscreen mode

βœ… 25. What is Bundle Analysis in Angular?

Used to inspect and reduce the size of the production bundle.

βœ… Tools:

  • Angular CLI:
ng build --stats-json
ng build --configuration production --stats-json
Enter fullscreen mode Exit fullscreen mode

Helps:

  • Find large packages
  • Remove unused code
  • Improve load time

βœ… 26. When to Use PUT and PATCH?

Method Use Case
PUT Replace the entire resource
PATCH Update part of the resource

Example:

// PUT - Replace
this.http.put('/api/user/1', userData);

// PATCH - Update only part
this.http.patch('/api/user/1', { name: 'New Name' });
Enter fullscreen mode Exit fullscreen mode

βœ… 27. What is the purpose of angular.json?

This is the Angular workspace configuration file.

It configures:

  • Build and serve targets
  • Assets, styles, scripts
  • File replacements (e.g., environments)
  • Linting and testing

βœ… 28. Angular 17 New Features (Highlights)

  • Deferrable Views: Lazy load components at a finer granularity using @defer
  • Control Flow Syntax: Built-in @if, @for, @switch (no more *ngIf, *ngFor)
  • Standalone Project Structure by Default
  • Signal-based reactivity (experimental)
  • Zone-less by default for faster change detection

βœ… 29. Difference: Standard Component vs Standalone Component

Feature Standard Component Standalone Component
Module required? Yes No
Declaration In @NgModule standalone: true
Angular 14+ ❌ βœ…

βœ… Example:

@Component({
  standalone: true,
  imports: [CommonModule],
  template: `...`
})
export class MyStandaloneComponent {}
Enter fullscreen mode Exit fullscreen mode

βœ… 30. What is bootstrapModule in Angular?

It's the method Angular uses to launch the root module.

βœ… Example:

platformBrowserDynamic().bootstrapModule(AppModule);
Enter fullscreen mode Exit fullscreen mode

In standalone component apps (Angular 17+), it can also bootstrap a component:

bootstrapApplication(AppComponent);
Enter fullscreen mode Exit fullscreen mode

βœ… 31. Angular Testing Framework

Angular uses Jasmine for writing tests and Karma for running them.

πŸ”Ή Key Concepts:

  • TestBed: Angular testing environment setup
  • Fixtures: Handle component instances
  • Spies: Mock services/functions

βœ… Example (Component Test):

describe('AppComponent', () => {
  let fixture: ComponentFixture<AppComponent>;
  let component: AppComponent;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [AppComponent]
    }).compileComponents();

    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
  });

  it('should create the component', () => {
    expect(component).toBeTruthy();
  });

  it('should have title "MyApp"', () => {
    component.title = 'MyApp';
    fixture.detectChanges();
    expect(component.title).toBe('MyApp');
  });
});
Enter fullscreen mode Exit fullscreen mode

βœ… 32. Pre-fetch Your Data Using Resolvers

Resolvers fetch data before navigating to a route.

βœ… Use case: Prevents component from loading with incomplete data.

βœ… Steps:

  1. Create a Resolver:
@Injectable({ providedIn: 'root' })
export class UserResolver implements Resolve<User> {
  constructor(private service: UserService) {}

  resolve(route: ActivatedRouteSnapshot): Observable<User> {
    return this.service.getUserById(route.paramMap.get('id'));
  }
}
Enter fullscreen mode Exit fullscreen mode
  1. Add it to route:
{
  path: 'user/:id',
  component: UserComponent,
  resolve: { user: UserResolver }
}
Enter fullscreen mode Exit fullscreen mode
  1. In component:
this.route.data.subscribe(data => {
  this.user = data.user;
});
Enter fullscreen mode Exit fullscreen mode

βœ… 33. Guard in Angular

Guards control access to routes.

πŸ”Έ Types:

  • CanActivate
  • CanDeactivate
  • CanLoad
  • Resolve
  • CanActivateChild

βœ… Example (CanActivate):

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(): boolean {
    if (!this.authService.isLoggedIn()) {
      this.router.navigate(['/login']);
      return false;
    }
    return true;
  }
}
Enter fullscreen mode Exit fullscreen mode

Apply it to route:

{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] }
Enter fullscreen mode Exit fullscreen mode

βœ… 34. HostBinding and HostListener

These allow interaction with the host element of the component or directive.

βœ… @HostBinding Example:

@HostBinding('class.active') isActive = true;
Enter fullscreen mode Exit fullscreen mode

βœ… @HostListener Example:

@HostListener('click', ['$event'])
onClick(event: Event) {
  console.log('Element clicked!', event);
}
Enter fullscreen mode Exit fullscreen mode

Used frequently in custom directives.


βœ… 35. Polyfill in Angular

Polyfills provide browser compatibility for features not supported in older browsers.

βœ… Config:

Check polyfills.ts file in Angular project.

// Example polyfill for ES6 features
import 'core-js/es6';
Enter fullscreen mode Exit fullscreen mode

Most modern Angular apps only need a few because of evergreen browser support.


βœ… 36. RouterOutlet in Angular

<router-outlet> acts as a placeholder where routed components are rendered.

βœ… Example:

<nav>
  <a routerLink="/home">Home</a>
</nav>

<router-outlet></router-outlet>
Enter fullscreen mode Exit fullscreen mode

Defined in app-routing.module.ts:

const routes: Routes = [
  { path: 'home', component: HomeComponent }
];
Enter fullscreen mode Exit fullscreen mode

βœ… 37. Can We Use Multiple <router-outlet>?

Yes β€” useful for layouts with named outlets.

βœ… Example:

<router-outlet></router-outlet>           <!-- Primary -->
<router-outlet name="popup"></router-outlet> <!-- Secondary -->
Enter fullscreen mode Exit fullscreen mode

Routes:

{
  path: 'help',
  component: HelpComponent,
  outlet: 'popup'
}
Enter fullscreen mode Exit fullscreen mode

Activate via:

this.router.navigate([{ outlets: { popup: ['help'] } }]);
Enter fullscreen mode Exit fullscreen mode

βœ… 38. Can I Write a Component Without a Constructor?

Yes β€” but only if the component does not need any DI services.

βœ… Minimal Example:

@Component({
  selector: 'app-hello',
  template: `<p>Hello!</p>`
})
export class HelloComponent {}
Enter fullscreen mode Exit fullscreen mode

If you need services like HttpClient, you’ll need a constructor.


βœ… 39. Pure Pipe vs Impure Pipe

Pipe Type Trigger
Pure (default) Called only when input changes
Impure Called on every change detection cycle

βœ… Pure Pipe Example:

@Pipe({ name: 'purePipe' })
export class PurePipe implements PipeTransform {
  transform(value: number): number {
    return value * 2;
  }
}
Enter fullscreen mode Exit fullscreen mode

βœ… Impure Pipe:

@Pipe({ name: 'impurePipe', pure: false })
Enter fullscreen mode Exit fullscreen mode

Use impure pipes carefully β€” they affect performance!


βœ… 40. FormBuilder vs FormGroup in Angular

Both are part of Reactive Forms.

Concept Use Case
FormGroup Manually create controls
FormBuilder Shorthand, more concise

βœ… FormGroup Example:

this.form = new FormGroup({
  name: new FormControl(''),
  age: new FormControl('')
});
Enter fullscreen mode Exit fullscreen mode

βœ… FormBuilder Example:

constructor(private fb: FormBuilder) {}

this.form = this.fb.group({
  name: [''],
  age: ['']
});
Enter fullscreen mode Exit fullscreen mode

βœ… 41. View Encapsulation in Angular (Recap)

Angular uses View Encapsulation to control style scoping.

πŸ”Έ Modes:

Mode Description
Emulated (default) Emulates Shadow DOM by adding unique attributes
None No encapsulation; styles are global
ShadowDom Uses browser-native Shadow DOM (real encapsulation)

βœ… Example:

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css'],
  encapsulation: ViewEncapsulation.Emulated
})
Enter fullscreen mode Exit fullscreen mode

βœ… Use Case:

  • Use None for global themes (e.g., Angular Material theming).
  • Use ShadowDom for strict style isolation.

βœ… 42. Difference Between Modules and Components

Feature Module Component
Purpose Group related components/services Represent UI elements/pages
Decorator @NgModule @Component
Structure Logical grouping Visual/UI rendering

βœ… Example:

@NgModule({
  declarations: [UserComponent],
  imports: [CommonModule],
})
export class UserModule {}

@Component({
  selector: 'app-user',
  template: `<p>User Component</p>`
})
export class UserComponent {}
Enter fullscreen mode Exit fullscreen mode

βœ… 43. Lazy Loading in Angular

Lazy loading loads modules on demand, improving initial load time.

βœ… Setup:

  1. Create a feature module (e.g., admin.module.ts)
  2. Use loadChildren in the route:
{
  path: 'admin',
  loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule)
}
Enter fullscreen mode Exit fullscreen mode

Ensure AdminModule has its own routing (AdminRoutingModule) with its components.


βœ… 44. Dynamic Component Loading

Use ViewContainerRef and ComponentFactoryResolver to load components dynamically.

βœ… Example:

@ViewChild('container', { read: ViewContainerRef }) container!: ViewContainerRef;

constructor(private cfr: ComponentFactoryResolver) {}

loadComponent() {
  import('./dynamic/dynamic.component').then(({ DynamicComponent }) => {
    this.container.clear();
    this.container.createComponent(DynamicComponent);
  });
}
Enter fullscreen mode Exit fullscreen mode

Template:

<ng-template #container></ng-template>
Enter fullscreen mode Exit fullscreen mode

βœ… 45. Change Detection in Angular

Angular uses zone.js to trigger change detection automatically on async events.

πŸ”Έ Strategies:

  • Default: Detects all changes (slower)
  • OnPush: Detects changes only for input-bound values

βœ… Example:

@Component({
  changeDetection: ChangeDetectionStrategy.OnPush
})
Enter fullscreen mode Exit fullscreen mode

βœ… Improve Performance:

  • Use OnPush when using immutables and @Input
  • Detach CD manually in performance-heavy components

βœ… 46. Zone.js in Angular

zone.js patches async APIs (e.g., setTimeout, Promise) to notify Angular of state changes.

πŸ”Ή Without zone.js, Angular wouldn't know when to run change detection.

With Angular 17, zone-less change detection using Signals is becoming the default.


βœ… 47. Signals in Angular 17

Signals offer a reactivity model without needing zone.js or manual subscription management.

βœ… Setup:

import { signal, computed, effect } from '@angular/core';

count = signal(0);

double = computed(() => this.count() * 2);

effect(() => console.log(this.double()));
Enter fullscreen mode Exit fullscreen mode

βœ… Benefit:

  • Fine-grained reactivity
  • Works without zones
  • Declarative like React’s useState/useEffect

βœ… 48. Standalone Components

No need for NgModules. Useful for reducing boilerplate.

βœ… Example:

@Component({
  selector: 'app-home',
  standalone: true,
  template: `<h1>Hello!</h1>`,
  imports: [CommonModule]
})
export class HomeComponent {}
Enter fullscreen mode Exit fullscreen mode

βœ… Bootstrap App with Standalone:

bootstrapApplication(HomeComponent);
Enter fullscreen mode Exit fullscreen mode

βœ… 49. Defer Blocks in Angular 17

@defer is used to lazy load parts of templates (not just routes!).

βœ… Example:

@defer (when visible) {
  <expensive-component></expensive-component>
}
Enter fullscreen mode Exit fullscreen mode

βœ… Use Cases:

  • Load chart, table, or modal only when visible
  • Improve First Contentful Paint (FCP)

βœ… 50. @Input, @Output vs Signals

Feature @Input/@Output Signals
Data Flow Parent β†’ Child / Child β†’ Parent Bi-directional and reactive
Reactive? No Yes
Boilerplate More Less
Angular Version Stable since v2 Angular 16+

βœ… Signal Example:

count = signal(0);

increment() {
  this.count.set(this.count() + 1);
}
Enter fullscreen mode Exit fullscreen mode

βœ… When to Use:

  • Use @Input/@Output for compatibility.
  • Use Signals for state management and zone-less CD in Angular 17+.

Top comments (0)