Open In App

RouterOutlet in Angular

Last Updated : 28 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

@Input() name: string

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);
});

supportsBindingToComponentInputs: true

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>
<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

projectstructure
Folder Structure

Dependencies

"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:


Next Article
Article Tags :

Similar Reads