apex charts angular

A Brief Tutorial on Using ApexCharts with Angular

apex charts angular


Quick Installation

  1. Install dependencies:

    npm i apexcharts ng-apexcharts
    
  2. Import Module (app.module.ts)

Basic Line Chart Example

Component Template (app.component.html)

<apx-chart 
  [series]="chartOptions.series" 
  [chart]="chartOptions.chart"
  [xaxis]="chartOptions.xaxis" 
  [title]="chartOptions.title">
</apx-chart>

Component Class (app.component.ts)

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  chartOptions = {
    series: [{ data: [10, 20, 30, 40] }],
    chart: { type: 'line' },
    xaxis: { categories: ['Jan', 'Feb', 'Mar', 'Apr'] },
    title: { text: 'Basic Line Chart' }
  };
}

Key Features

  1. Dynamic Updates

    updateChart() {
      const newData = this.chartOptions.series[0].data.map(() => 
        Math.floor(Math.random() * 100)
      );
      this.chartOptions = { ...this.chartOptions, series: [{ data: newData }] };
    }
    
  2. Mixed Chart Types – Ability to use multiple chart types in one visualization.

Example Links

Basic Demo: Pie Chart

chartOptions = {
  series: [44, 55, 13],
  chart: { type: 'pie', width: 380 },
  labels: ['Team A', 'Team B', 'Team C']
};

Common Configurations

Styling

chartOptions = {
  chart: { foreColor: '#333' }, // Text color
  colors: ['#4CAF50', '#E91E63'], // Data colors
  grid: { borderColor: '#e0e0e0' } // Grid lines
};

Tooltip Customization

tooltip: {
  theme: 'dark',
  x: { show: false }, // Hide x-axis tooltip
  y: { formatter: (val: number) => `${val} users` } // Custom label
}

Tips for Troubleshooting

  1. Chart Not Rendering?

    • Make sure NgApexchartsModule is imported.
    • Ensure there are no typos with option properties (e.g., xaxis vs xAxis).
  2. Data Not Updating?

    • Assign the entire chartOptions object to enable Angular change detection.
  3. Performance Issues?

    • Use ChangeDetectionStrategy.OnPush for optimization.
    • Debounce quick updates usingrxjs/debounceTime .

Why ApexCharts?

Free & Open Source

  • MIT Licensed

Advanced Features

  • Chart Annotations
  • Data Labels
  • Brush Charts

Native Angular Support

  • Ready-to-use code snippets

For more advanced features like annotations, data labels, brush charts, and others, check out the ApexCharts Documentation.


Angular chart library Highcharts

Highcharts with Angular

Highcharts is a powerful JavaScript library for creating interactive charts and graphs. When combined with Angular, a robust framework for building web applications, you can create dynamic, data-driven visualizations with ease. This guide will walk you through integrating Highcharts into an Angular project, from setup to advanced configurations.

highcharts angular

Why Highcharts with Angular?

  • Rich Features: Supports line, bar, pie, scatter, and complex charts such as heatmaps.
  • Interactivity: Zooming in and out, tooltips, and dynamic updates enhance user engagement.
  • Customization: Theming, annotations, and responsive design.
  • Angular Compatibility: The official highcharts-angular wrapper simplifies integration. Say goodbye to expensive custom solutions!

Prerequisites

  • Node.js and npm tools installed.
  • Angular CLI:
    npm install -g @angular/cli
    
  • Basic knowledge of Angular components and modules.

Project Setup

  1. Create an Angular Project
    ng new highcharts-angular-demo
    cd highcharts-angular-demo
    
  2. Install Dependencies Install Highcharts and Angular wrappers:
    npm install highcharts highcharts-angular
    

Basic Integration

1. Import HighchartsModule

Add HighchartsModule to app.module.ts:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { HighchartsChartModule } from 'highcharts-angular';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, HighchartsChartModule],
  bootstrap: [AppComponent]
})
export class AppModule {}

2. Create a Chart Component

Inapp.component.ts, define chart options:

import { Component } from '@angular/core';
import * as Highcharts from 'highcharts';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  Highcharts: typeof Highcharts = Highcharts;
  chartOptions: Highcharts.Options = {
    title: { text: 'Monthly Sales' },
    series: [{ type: 'line', data: [1, 2, 3, 4, 5] }]
  };
}

In app.component.html, render the chart:

<highcharts-chart
  [Highcharts]="Highcharts"
  [options]="chartOptions"
  style="width: 100%; height: 400px; display: block;">
</highcharts-chart>

3. Run the App

ng serve

Visit http://localhost:4200 and see your chart!

Dynamic Charts

Update charts reactively using Angular data binding.

1. Add a Button to Update Data

In app.component.html:

<button (click)="updateData()">Add Data</button>

2. Implement Data Update Logic

In app.component.ts:

export class AppComponent {
  //...existing code...
  updateData() {
    this.chartOptions = {
      ...this.chartOptions,
      series: [{ type: 'line', data: [...this.chartOptions.series[0].data, Math.random() * 10] }]
    };
  }
}

Configuration & Customization

1. Chart Types

Change type in series to 'bar', 'pie', etc.:

series: [{ type: 'bar', data: [10, 20, 30] }]

2. Styling

Customize colors, axes, and tooltips:

chartOptions: Highcharts.Options = {
  chart: { backgroundColor: '#f4f4f4' },
  xAxis: { title: { text: 'Month' } },
  yAxis: { title: { text: 'Sales' } },
  tooltip: { valueSuffix: ' units' }
};

3. Exporting

Enable exporting to PNG/PDF:

exporting: { enabled: true }

Advanced Features

1. Highcharts Modules

Import additional features like 3D charts:

npm install highcharts-3d

In app.component.ts:

import HC_3D from 'highcharts/highcharts-3d';
HC_3D(Highcharts);

2. Lazy Loading Chart

Load charts on demand using Angular's ngOnInit:

async ngOnInit() {
  const Highcharts = await import('highcharts');
  // Initialize chart here
}

3. Performance Optimization

  • Use OnPush change detection.
  • Debounce rapid data updates.

Common Issues & Solutions

  1. Chart Not Updating: Reassign chartOptions instead of mutating it.
  2. Missing Dependencies: Ensure highcharts andhighcharts-angular versions match.
  3. Resize Issues: CallHighcharts.charts[0].reflow() on window resize.

Highcharts and Angular together offer a powerful toolkit for data visualization. This guide has enabled you to set up, customize, and optimize charts in an Angular app. Explore the Highcharts documentation for more advanced features such as stock charts or accessibility options.


how to merge objects in javascript

There are various ways to combine two objects in JavaScript. Whether you want to conduct a shallow or deep merge will determine which technique you use.

merge objects in javascript


1. Shallow Merge (Overwrite Properties)

  • Using Object.assign():

const obj1 = { a: 1, b: 2 };

const obj2 = { b: 3, c: 4 };


const merged = Object.assign({}, obj1, obj2);

// Result: { a: 1, b: 3, c: 4 }

  • Using the Spread Operator (...):

const merged = {...obj1,...obj2 };

// Result: { a: 1, b: 3, c: 4 }

Note: Both methods are shallow merges—nested objects/arrays are all by reference (not cloned). If there are duplicate keys, subsequent properties will overwrite prior ones.

2. Deep Merge (Recursively Combine Nested Properties)

  • Using Lodash:

const merged = _.merge({}, obj1, obj2);

  • Custom Deep Merge Function (Simplified Example):

function deepMerge(target, source) {

for (const key in source) {

if (source[key] instanceof Object && target[key]) {

deepMerge(target[key], source[key]);

} else {

target[key] = source[key];

}

}

return target;

}


const merged = deepMerge({}, { a: { x: 1 } }, { a: { y: 2 } });

// Result: { a: { x: 1, y: 2 } }

Other Considerations

  • Shallow Merge: For simple scenarios, employ Object.assign() or the spread operator.
  • Deep Merge: For greater resilience, use a tool such as Lodash (e.g. _.merge()), which is able to contend with sophisticated structures, including arrays and null values
  • Overwriting Behavior: In situations involving conflict over keys, later objects always win.

Preventdefault vs stoppropagation javascript

 Here is a brand new essay about preventDefault() versus stopPropagation() in Angular. I'll start by comparing how they're used with preventDefault() and stopPropagation. We'll also offer a case study for each method and share some tips.

preventdefault vs stoppropagation javascript angular


1. event.preventDefault() in Angular

  • Purpose: To prevent the default action of a browser event (for example, a submission form or hyperlink).
  • Use in Angular: With Angular’s event binding syntax (event)="handler($event)"
.

Example: Prevent link from navigating:

<a href="https://dangerous.com" (click)="onLinkClick($event)">Dangerous Link</a>
onLinkClick(event: MouseEvent) {
  event.preventDefault(); // Stop navigation
  // Custom logic here (e.g., show a modal instead)
}
  • Scenarios Commonly Encountered in Angular:
    • When using (submit) and <form> to cancel form submission.
    • Shut off the default behaviors of anchor tags, buttons, or form fields.

2. event.stopPropagation() in Angular

  • Purpose: Stop event bubbling/capturing in the DOM tree.
  • Use in Angular: To prevent parent and descendant components from receiving the exact same events.

Example: Don't let a press on a button cause the parent <div> method to fire:

<div (click)="onParentClick()">
  <button (click)="onButtonClick($event)">Click Me</button>
</div>
onButtonClick(event: MouseEvent) {
  event.stopPropagation(); // The mom's onParentClick() will not fire
  // Take care of button click
}
  • Specific Cases:
    • Stop nested components from propagating events.
    • Avoid conflict with other handlers dealing in similar space (e.g., dropdown, modals).

3. Key Differences in Angular

preventDefault() stopPropagation()
Focus Prevent browser from default behavior (e.g., form submit) Prevent DOM event bubbling/capturing
Use Case in Angular Cancel navigation, form submission Parent and child Components surface events in their own spaces
Template Syntax (submit)="onSubmit($event)" (click)="onClick($event)"

4. Using Both Together in Angular

Example: Handle a custom form action without submitting and prevent parent components from interpreting it:

<form (submit)="onFormSubmit($event)">
  <button type="submit">Save</button>
</form>
onFormSubmit(event: Event) {
  event.preventDefault(); // Halt the default form submission
  event.stopPropagation(); // Don't let parent events hear about this
  this.saveData(); // Custom logic here, e.g. http call
}

5. Angular Special Notes

Event Modifiers

Angular does not provide its own event modifiers like Vue's .prevent or .stop. You need to call the method explicitly instead:

<form (submit)="onSubmit($event)"></form>
onSubmit(event: Event) {
  event.preventDefault(); // Manually call
}

Component Communication

  • stopPropagation() only affects DOM events, not Angular's @Output().

Example:

<app-child (customEvent)="onChildEvent()"></app-child>
// ChildComponent
@Output() customEvent = new EventEmitter();
emitEvent() {
  this.customEvent.emit();
  // Whether the parent code listens to DOM event propagation, onChildEvent() will fire
}

Change Detection

  • Neither method affects Angular change detection.
  • Use NgZone or ChangeDetectorRef when events bypass Angular's domain (for example, setTimeout).

6. Angular Best Practices

  1. How to Break Free from Inline Calls: Place your methods right in the constituent, rather than inside the official template:

    <a href="#" (click)="onClick($event)">Link</a>
    <button (click)="onClick($event)">Link</button>
    
  2. For Component Communication, Use EventEmitter : Old-fashioned emit rather than DOM event. Use @Output() Stateless Copy for State Changes: Ensure data is never changed after a call to preventDefault(), to be sure change detection fires.


7. Common Traps

  • Lack of $event: Don’t forget to mention $event in the template:

    <button (click)="onClick">Click</button> ❌ Incorrect
    <button (click)="onClick($event)">Click</button> ✅ Correct
    
  • Too Much stopPropagation(): For highly intricate component trees, it can only create debugging headaches.

In Angular:

  • preventDefault(): Regulate browser defaults (e.g., forms, links).
  • stopPropagation(): Control event flow between some connected DOM elements/components.
  • Use both in tandem to finely manage your event firing and your UI experience.


ng-template & ng container in angular

 In an Angular application, the user interface is the fact: the tags themselves, stored in a template file. Most developers are familiar with both components and directives. However, the ng-template directive is a powerful but often misunderstood tool. This blog will teach you what ng-template is, provide some examples, and show how it lets Angular applications display advanced UI patterns.
Understanding ng-template and ng-container in Angular

What is ng-template?

ng-template is an Angular directive that specifies a template block not to be rendered by the browser by default. Instead, it is treated as a blueprint for making dynamic places: when combined with structural directives such as *ngIf, *ngFor, or your own, one of the above might as well be called a register. Here is a way to save.

Characteristics

  1. Not Rendered at the Beginning: It's as if everything inside ng-template were dull, waiting for approval.
  2. Collaborates with Structural Directives: Used to mark content which depends on something like a condition you may want to show a larger view of or data that is supposed to not just go away.
  3. Takes Contextual Information: Lets you pass data to templates for dynamic rendering.

Basic Usage of ng-template

Example 1: Conditional Rendering with *ngIf and else

This is a common use case where alternate content is shown when a particular condition isn’t true:

<div *ngIf="userLoggedIn; else loginPrompt">
  Welcome, {{ username }}!
</div>

<ng-template #loginPrompt>
  <p>Please log in.</p>
</ng-template>

Here:

  • The else clause calls the loginPrompt template.
  • The loginPrompt template only gets rendered when userLoggedInis false.

How It Works:

Angular converts the *ngIf syntax into:

<ng-template [ngIf]="userLoggedIn">
  <div>Welcome, {{ username }}!</div>
</ng-template>

The #loginPrompt is a template reference variable pointing to the ng-template.

The Role of Structural Directives

Structural directives (e.g., *ngIf, *ngFor) manipulate the DOM by adding or removing elements. As it turns out, they use ng-template to define the content they manage.

Example 2: How *ngFor Uses ng-template

This code:

<ul>
  <li *ngFor="let item of items; let i = index">{{ i }}: {{ item }}</li>
</ul>

Turns into this thanks to Angular:

<ul>
  <ng-template ngFor let-item [ngForOf]="items" let-i="index">
    <li>{{ i }}: {{ item }}</li>
  </ng-template>
</ul>

The contents of ng-template provide the structure that gets repeated for each item in items .

Advanced Use Cases

1. Dynamic Templates with ngTemplateOutlet

Use ngTemplateOutlet to render a template dynamically, optionally with context data:

@Component({
  template: `
    <ng-container *ngTemplateOutlet="greetingTemplate; context: { $implicit: 'User' }">
    </ng-container>

    <ng-template #greetingTemplate let-message>
      Welcome, {{ message }}!
    </ng-template>
  `
})

Here:

  • ngTemplateOutlet displays greetingTemplate, together with context information.
  • let-message gets the context's $implicit value.

2. Custom Structural Directives

Create reusable directives that leverage ng-template:

@Directive({
  selector: '[appRepeat]'
})
export class RepeatDirective {
  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef
  ) {}

  @Input() set appRepeat(times: number) {
    this.viewContainer.clear();
    for (let i = 0; i < times; i++) {
      this.viewContainer.createEmbeddedView(this.templateRef, { $implicit: i + 1 });
    }
  }
}

Usage:

<ul>
  <li *appRepeat="3">Item {{ count }}</li>
</ul>

Output:

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>
3. Content Projection with ng-content and Templates
Pass templates to components as inputs for flexible content projection.
Parent Component:

<app-card>
<ng-template #header>My Custom Header</ng-template>
<ng-template #body>Body: {{ data }}</ng-template>
</app-card>
@Component({
selector: 'app-card',
template: `
<div class="card">
<ng-container *ngTemplateOutlet="headerTemplate"></ng-container>
<ng-container *ngTemplateOutlet="bodyTemplate; context: { data: cardData }"></ng-container>
</div>
`,
})
export class CardComponent {
@ContentChild('header') headerTemplate!: TemplateRef<any>;
@ContentChild('body') bodyTemplate!: TemplateRef<any>;
cardData = 'Sample data';
}

ng-template vs. ng-container

Featureng-templateng-container
RenderingNot rendered by defaultRendered as a lightweight container
Use CaseDefine reusable template blocksGroup elements without adding extra DOM nodes
Structural DirectivesRequires a directive to renderCan host structural directives directly
Best Practices

Child Component (app-card):
  • Avoid Overuse of Templates: Use ng-template only when necessary to keep the DOM clean.

  • Pass Data Through Context: Use context objects for dynamic template rendering.

  • Combine with ng-container: Use ng-container for grouping structural directives to prevent unnecessary DOM elements.

What is changedetector and its use in agular

 Throwing Yourself into ChangeDetector in Angular: Sinking Your Doe into Performance

When traditional web frameworks make the user interface (UI) just one big application that responds to all its own new data, the main job of change detection is to stop this from breaking down. In Angular, this duty is managed by an advanced change detection mechanism.

The core of this mechanism is ChangeDetectorRef, a powerful tool for optimizing performance and regulating how and when Angular updates the DOM. In this article, we will examine what ChangeDetectorRef can do, how it does it, and how it is used in practice.

What is Change Detection in Angular?

Before sinking into ChangeDetectorRef, let’s get an initial understanding of change detection.

Angular applications are dynamic: data changes over time owing to user interactions, API calls, or via timers. When data changes, Angular needs to update the DOM so that it reflects the new state of affairs. This job of synchronizing the data model with the UI is called change detection.

Angular’s default change detection strategy observes all components in the application every time an event occurs (e.g., click, HTTP response, or timer tick). While this method ensures accuracy, it can become inefficient as the application size and component tree structure increase since it requires all components to be checked.

To address this problem, Angular provides help for speeding up certain aspects of the transfer of information, such as the ChangeDetectorRef class.

What is ChangeDetectorRef?

ChangeDetectorRef is a class provided by Angular’s @angular/core module. It allows developers to manage a component’s change detection system directly. By using ChangeDetectorRef, you can optimize performance by reducing unnecessary checks or forcing updates when needed.

Key Methods of ChangeDetectorRef

Let’s look at the four principal methods of ChangeDetectorRef:

  1. detectChanges()
  • What it does: Triggers change detection immediately for the present component and its children.
  • Use case: After modifying data outside Angular’s awareness (e.g., in a setTimeout or third-party library callback), update the UI.
import { Component, ChangeDetectorRef } from '@angular/core';

@Component({
  selector: 'app-example',
  template: `{{ data }}`
})
export class ExampleComponent {
  data: string;

  constructor(private cdr: ChangeDetectorRef) {
    setTimeout(() => {
      this.data = 'Updated!';
      this.cdr.detectChanges(); // Manually trigger update
    }, 1000);
  }
}
  1. markForCheck()
  • What it does: Marks the present component and its ancestors for check during the next change detection cycle. Used with OnPush strategy.
  • Use case: Notify Angular to check a component when its inputs change or internal state is updated.
@Component({
  selector: 'app-onpush',
  template: `{{ counter }}`,
  changeDetection: ChangeDetectionStrategy.OnPush // Optimize with OnPush
})
export class OnPushComponent {
  counter = 0;

  constructor(private cdr: ChangeDetectorRef) {}

  increment() {
    this.counter++;
    this.cdr.markForCheck(); // Schedule check for next cycle
  }
}
  1. detach() and reattach()
  • What they do:
    • detach(): Automatically disables change detection on the component.
    • reattach(): Re-enables it.
  • Use case: Temporarily cease change detection within performance-critical sections.
export class DetachExampleComponent {
  constructor(private cdr: ChangeDetectorRef) {
    this.cdr.detach(); // Disable auto-checking
  }

  updateData() {
    // Changes here won't reflect on the UI until reattached
    this.cdr.reattach(); // Re-enable checking
    this.cdr.detectChanges();
  }
}

Use Cases for ChangeDetectorRef

  1. Optimizing Performance with OnPush

The OnPush change detection strategy reduces checks down to only the present component and its ancestors by carrying out operations only when:

  • Input properties change.
  • A component emits an event (e.g., clicking a button).
  • markForCheck() is called.

Using ChangeDetectorRef.markForCheck() with OnPush reduces the number of non-essential checks, which improves performance when applications grow large or have complex component structures.

  1. Integrating Third-Party Libraries

By using non-Angular libraries (e.g., D3.js or jQuery plugins), data changes can occur outside the reach of Angular’s zone. In these cases, you have to use detectChanges() to update the UI.

ngAfterViewInit() {
  const chart = d3.select(this.elementRef.nativeElement).append('svg')
  //... setup chart
  chart.on('click', () => {
    this.selectedData = newData;
    this.cdr.detectChanges(); // Force UI update
  });
}
  1. Managing Async Operations Outside Angular’s Zone

By default, Angular performs change detection when async operations (e.g., setTimeout) finish. If you run code outside Angular’s zone (via NgZone.runOutsideAngular), you must use detectChanges() to update.

constructor(private ngZone: NgZone, private cdr: ChangeDetectorRef) {
  this.ngZone.runOutsideAngular(() => {
    setTimeout(() => {
      this.data = 'Updated outside Angular!';
      this.cdr.detectChanges(); // Manual update
    }, 1000);
  });
}

Best Practices and Pitfalls

  • Avoid Overusing Manual Detection: Wherever possible, rely on Angular’s default mechanism. Overuse of detectChanges() will complicate debugging.
  • Combine with OnPush: Use markForCheck() to maximize performance gains.
  • Reattach Detached Components: Forgetting to reattach a component can cause the UI to become stale.
  • Unsubscribe from Observables: To prevent memory leaks, always clean up subscriptions.

Conclusion

Angular’s ChangeDetectorRef gives developers fine-grained control over change detection, making it a powerful tool for optimizing application performance. Whether you’re refactoring operations with OnPush, integrating third-party libraries, or managing async operations outside Angular’s zone, understanding ChangeDetectorRef is essential.

By strategically using detectChanges(), markForCheck(), and detach(), you can ensure that your Angular applications perform efficiently.

And remember: with great power comes great responsibility—use these techniques wisely to maintain code quality and application stability.


router-outlet and it's purpose

Understanding <router-outlet> in Angular and Its Purpose

In Angular, the <router-outlet> directive plays an important role in navigation and showing components dynamically based on the router configuration of the application. Let's see more about its purpose, how it works, and a few advanced use examples.

Understanding `router-outlet` and Its Purpose in Angular


What is <router-outlet>?

<router-outlet> is an Angular built-in directive used as a placeholder for dynamically loaded routed components based on the application's router configuration. It acts as a viewport where Angular inserts the content of the active route.

Purpose of <router-outlet>

  • Dynamic Component Loading: It allows Angular to render different components based on the URL path.
  • Single Page Application (SPA): It helps build SPAs by loading only those parts of a page that are needed without reloading it entirely.
  • Supports Nested Routing: Multiple <router-outlet> elements can be used to create child routes and complex navigation structures.
  • Smooth Transitions: Enables seamless navigation between views without requiring a page refresh.

How <router-outlet> Works

Step 1: Define Routes in app-routing.module.ts

import { NgModule } from "@angular/core";  
import { RouterModule, Routes } from "@angular/router";  
import { HomeComponent } from "./home/home.component";  
import { AboutComponent } from "./about/about.component";  

const routes: Routes = [  
  { path: "", component: HomeComponent },  
  { path: "about", component: AboutComponent }  
];  

@NgModule({  
  imports: [RouterModule.forRoot(routes)]  
})  
export class AppRoutingModule { }  

Step 2: Add <router-outlet>to app.component.html

<nav>  
  <a routerLink="/">Home</a>  
  <a routerLink="/about">About</a>  
</nav>  

<router-outlet></router-outlet>  
  • Clicking on Home (/) will load HomeComponent inside <router-outlet>.
  • Clicking on About (/about) will load AboutComponent dynamically into <router-outlet>.

Using Multiple <router-outlet> for Nested Routing

If your application has a three-level navigation structure (Parent → Child → Grandchild), you can use multiple <router-outlet> elements.

Example: Parent-Child Routing

const routes: Routes = [  
  {  
    path: 'dashboard', component: DashboardComponent,  
    children: [  
      { path: 'profile', component: ProfileComponent },  
      { path: 'settings', component: SettingsComponent }  
    ]  
  }  
];  

dashboard.component.html

<h2>Dashboard</h2>  
<a routerLink="profile">Profile</a>  
<a routerLink="settings">Settings</a>  

<router-outlet></router-outlet> <!-- Child items are mounted here -->
  • Enter /dashboard/profile, and DashboardComponent will be shown.
  • ProfileComponent will be displayed inside the <router-outlet> inside DashboardComponent.

Named <router-outlet>for Multiple Views

You can use named outlets to render multiple views in different containers.

<router-outlet name="primary"></router-outlet>  
<router-outlet name="sidebar"></router-outlet>  

This way, you can create layouts with multiple views.

<router-outlet>is essential in Angular for navigation and dynamic component loading. It enables the creation of complex applications with nested routes, lazy loading, and multiple views.

Select Menu