What problems does this solve?
- This enables you to have an Angular application alongside your Umbraco website, on a specified route.
- The Angular App can be protected by the Authentication of your website, if you have it. And you can make use of surface controllers for authenticated requests.
- The routing of your app will work as intended, for example, if your Angular app is at /app and you make a request to /app/products, the request will be routed to the angular app products’ page.
What this is not
- A complete front end for a Umbraco website with dynamic routes.
- This doesn’t have dynamic routes, you have to specify them on your code.
Let’s get started!
First, start by creating a controller to handle the Angular App request.
using System.Web.Mvc; public class AngularAppController : BaseController { public ActionResult AngularAppView() { return View(); } }
Then, you have to decide the route where your Angular app will render. On this example it will be /angularapp.
On your ApplicationStarted method, put this code:
RouteTable.Routes.MapRoute( "AngularApp", "angularapp/{*.}", new { controller = "AngularApp", action = "AngularAppView" });
The {*.} syntax is what makes your angular app routes load and not return the 404 page.
If you don’t have an ApplicationStarted method, find out how you to create it here: https://our.umbraco.org/documentation/reference/events/application-startup
Under your Views folder, create a folder with the same name as the controller you set in MapRoute. In this case it will be “AngularApp”.
Inside it, create a view with the same name as the action set you set in MapRoute.
Inside the view put the contents of the index.html of your angular app.
Then you will need to move your angular app files somewhere like you /Assets folder, and edit their paths on the view.
Almost done!
Now you need to edit the routes of your Angular app.
Simply add the route you chose as a prefix to the routes.
From something like this:
const routes: Routes = [ { path: '', redirectTo: '/dashboard', pathMatch: 'full' }, { path: '/dashboard', component: DashboardComponent }, { path: '/detail/:id', component: HeroDetailComponent }, { path: '/heroes', component: HeroesComponent } ];
To this:
const routes: Routes = [ { path: 'angularapp', redirectTo: 'angularapp/dashboard', pathMatch: 'full' }, { path: 'angularapp/dashboard', component: DashboardComponent }, { path: 'angularapp/detail/:id', component: HeroDetailComponent }, { path: 'angularapp/heroes', component: HeroesComponent } ];
Thanks for reading!
Mário
Hey man – nice article. Will this work with the newer versions of Angular like Angular 10?
Hey, yes it does 🙂