0

Angular 6/7/8/9 Integration With ASP.Net Web Form

Hi Friends, In this article, I will explain to you, how to integrate angular 6/7/8/9 projects with existing asp.net project with web forms.

First create one angular project.

Create AngularIntegration.aspx page in asp.net project and add reference of js files form angular project dist folder to asp.net project.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AngularIntegration.aspx.cs" %>  
<!DOCTYPE html>  
<html xmlns="http://www.w3.org/1999/xhtml">
   <head runat="server">
      <title></title>
      <base href="/">
   </head>
   <body>
      <form id="form1" runat="server">
         <div>
            <app-root name=""></app-root>
            <script defer="defer" src="<%= ResolveUrl("main-es2015.js") %>"></script>
            <script defer="defer" src="<%= ResolveUrl("polyfills-es2015.js") %>"></script>
            <script defer="defer" src="<%= ResolveUrl("runtime-es2015.js") %>"></script>
            <script defer="defer" src="<%= ResolveUrl("styles-es2015.js") %>"></script>
            <script defer="defer" src="<%= ResolveUrl("vendor-es2015.js") %>"></script>		
         </div>
      </form>
   </body>
</html>

Add below script for dynamic routing based on the query string

<script type="text/javascript">
   document.getElementsByTagName("app-root")[0].setAttribute("name", getUrlParameter("p"));
   
   function getUrlParameter(name) {
       name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
       var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
       var results = regex.exec(location.search);
       return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
   };
   
   
</script>

app.component.ts file code

import { Component, ElementRef, Input } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {

@Input('name') name: string;
constructor(private router: Router, private route: ActivatedRoute, private eleRef: ElementRef) { }

ngOnChanges() {

}

ngOnInit(): void {
this.router.navigateByUrl('/' + this.eleRef.nativeElement.getAttribute('name'), { skipLocationChange: true });
}
}

app-routing.modules.ts code

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { TestComponent } from './test/test.component';

const routes: Routes = [
   {path: 'test', component: TestComponent}
  ];

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

Now you can run your angular project in asp.net web form project. Please find below example

Ex. http://localhost:80/AngularIntegration.aspx?p=test

Value of query string p is value of routing path in angular project.

Santosh Shelar

Leave a Reply

Your email address will not be published. Required fields are marked *