The Angular RouterOutlet directive serves as a placeholder that Angular fills dynamically based on the current route. RouterOutlet is important in the creation of Single Page Applications (SPAs) since it provides component display mode depending on the URL without the entire page refreshing. Thus, it allows developers to create seamless navigation by rendering appropriate components for certain routes within the application layout.
Prerequisites
Role of RouterOutlet in Angular Applications
RouterOutlet gives Angular apps the capability of managing dynamic content rendering influenced by pathing setups. It allows for displaying routed components without having to reload the entire webpage, which is why it is vital in the creation of effective single-page applications (SPAs).
RouterOutlet Directive
In accordance with the routing configuration of any application created with Angular, the RouterOutlet directive serves as a kind of home base where different routed components are loaded and displayed dynamically by Angular.
Syntax:
<router-outlet></router-outlet>
Key Properties and Methods
Name property: Defining multiple places in a single component. This is useful when there are different RouterOutlet instances needed on the same page.
Example:
<router-outlet name="primary"></router-outlet>
<router-outlet name="aux"></router-outlet>
@Output('activate') activateEvents: EventEmitter<any>
Emits on when component activates:
When one of the components in the RouterOutlet gets activated, then an event is generated.
Syntax:
this.routerOutlet.activateEvents.subscribe(component => {
console.log('Activated component:', component);
});
@Output('deactivate') deactivateEvents: EventEmitter<any>
When a Component is Deactivated it Emits:
An event that is emitted when a Component is deactivated in RouterOutlet.
Syntax:
this.routerOutlet.deactivateEvents.subscribe(component => {
console.log('Deactivated component:', component);
});
@Output('attach') attachEvents: EventEmitter<unknown>
Connected when a component is attached to the RouterOutlet; emits an event.
Syntax:
this.routerOutlet.attachEvents.subscribe(event => {
console.log('Component attached:', event);
});
@Output('detach') detachEvents: EventEmitter<unknown>
Emit When a component is removed from RouterOutlet, it emits an event.
Syntax:
this.routerOutlet.detachEvents.subscribe(event => {
console.log('Component detached:', event);
});
It indicates that RouterOutlet enables a component input to bind itself dynamically with data; therefore, it has been referred to as the “support for binding to component inputs.”
Example:
<router-outlet [someInput]="data"></router-outlet>
isActivated: boolean
Activation State:
Indicates whether RouterOutlet is currently active or not.
Syntax:
if (this.routerOutlet.isActivated) {
console.log('RouterOutlet is activated');
}
component: Object
Reference to the Activated Component is made by this statement:
This statement refers to the currently active component in the RouterOutlet.
Syntax:
const activeComponent = this.routerOutlet.component;
console.log('Active component:', activeComponent);
activatedRoute: ActivatedRoute
Activate the route: Get current activated route containing details about the active one.
Syntax:
const routeInfo = this.routerOutlet.activatedRoute;
console.log('Activated route info:', routeInfo);
activatedRouteData: Data
Use the information connected to the ActivatedRoute that is presently working.
Syntax:
const routeData = this.routerOutlet.activatedRouteData;
console.log('Route data:', routeData);
Basic RouterOutlet
Most simply, you could implement RouterOutlet by integrating it into any template where you want the routed component to show up. This is the default mode of using it, and this applies to a typical primary section of the application.
The common use case is a standard RouterOutlet. This acts as the access point for routed content in the Angular application. The component associated with the current route is displayed inside this outlet.
Syntax:
<router-outlet></router-outlet>
Example:
Let us consider a simple Angular application with two routes: '/home' and '/about'. The 'RouterOutlet' directive is placed in the main template (ex: 'app.component.html')
Step 1. Define routes in 'app.routes.ts':
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' }
];
Step 2. Use 'RouterOutlet' in the main template:
<nav>
<a routerLink="/home">Home</a>
<a routerLink="/about">About</a>
</nav>
<router-outlet></router-outlet>
The above examples work by navigating to '/home' or '/about' will render 'HomeComponent' or 'AboutComponent', respectively in the 'RouterOutlet' location.
Named Outlets
In sophisticated situations, Angular provides named outlets that can be used to show various views at the same time in different areas of a page. Named outlets are advantageous for implementing secondary routes or projecting several components on the surface of a screen.
By utilizing named outlets, you can display various components in different sections of a page at once. This technique benefits especially auxiliary routes or layouts, as they depend on having multiple content areas that can be refreshed without impacting each other.
Syntax:
<router-outlet name="primary"></router-outlet>
<router-outlet name="aux"></router-outlet>
Example:
Let's extend the previous above example to include a named outlet for an auxiliary route.
Step 1 .Define routes with a named outlet:
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'contact', component: ContactComponent, outlet: 'aux' },
{ path: '', redirectTo: '/home', pathMatch: 'full' }
]
Step 2. Use named 'RouterOutlet' in the template:
<nav>
<a routerLink="/home">Home</a>
<a routerLink="/about">About</a>
</nav>
<router-outlet></router-outlet>
<router-outlet name="aux"></router-outlet>
Step 3 .Navigate to an auxiliary route using 'routerLink':
<a [routerLink]="[{ outlets: {aux: ['contact'] } }]">Contact</a>
When the 'ContactComponent' is activated by the auxiliary route, it will render in the 'aux' outlet while the primary content remains unchanged.
Steps To Implement RouterOutlet in Angular
Step 1: Install Angular CLI:
If you have not installed Angular CLI, install it by using the following command.
npm install -g @angular/cli
Step 2: Create a new Angular project
ng new angular-routeroutlet-demo
Step 3: Navigate to the Project Directory
cd angular-routeroutlet-demo
Step 4: Generate Components
ng generate component home
ng generate component about
ng generate component contact
Folder Structure
Folder StructureDependencies
"dependencies": {
"@angular/animations": "^18.0.0",
"@angular/common": "^18.0.0",
"@angular/compiler": "^18.0.0",
"@angular/core": "^18.0.0",
"@angular/forms": "^18.0.0",
"@angular/platform-browser": "^18.0.0",
"@angular/platform-browser-dynamic": "^18.0.0",
"@angular/platform-server": "^18.0.0",
"@angular/router": "^18.0.0",
"@angular/ssr": "^18.0.0",
"express": "^4.18.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}
Example
Let's create a simple Angular app with 'HomeComponent', 'AboutComponent' and 'ContactComponent'. The 'HomeComponent' and 'AboutComponent' will be displayed in the primary 'RouterOutlet', while 'ContactComponent' will be displayed in a named outlet.
App Component
Below mentioned is the code example of App Component demonstrating the use of Router Outlet in Angular.I the given example, we are having app.component.html, app.component.ts and app.routes.ts showing the use of Router Outlet using three components.
HTML
<!--src/app/app.component.html-->
<nav>
<a routerLink="/home">Home</a><br>
<a routerLink="/about">About</a><br>
<a [routerLink]="[{ outlets: { aux: ['contact'] } }]">Contact</a>
</nav>
<router-outlet></router-outlet>
<router-outlet name="aux"></router-outlet>
JavaScript
//app.routes.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { ContactComponent } from './contact/contact.component';
export const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'contact', component: ContactComponent, outlet: 'aux' },
{ path: '', redirectTo: '/home', pathMatch: 'full' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
JavaScript
//app.component.ts
import { Component } from '@angular/core';
import { RouterOutlet, RouterModule } from '@angular/router';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, RouterModule],
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'angular-routerloutlet-demo';
}
About Component
Below is the HTML code of about component which on being redirected to about component displays 'about' as the information being displayed.
HTML
<!-- app/about/about.component.html -->
<p>about</p>
Home Component
Below is the HTML code of home component which on being redirected to home component displays 'home' as the information being displayed.
HTML
<!-- app/home/home.component.html -->
<p>home</p>
Contact Component
Below is the HTML code of Contact component which on being redirected to Contact component displays 'Contact' as the information being displayed.
HTML
<!-- app/contact/contact.component.html -->
<p>contact</p>
Add the above codes in the appropriate files, and use the below command to start the application:
ng serve
Output:
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read