Embedding Angular in Rails partial view
Angular JS is designed to operate as a full stack frontend framework, but sometimes we may need to embed some JS component with complicated logic into existing pages. Usually, React or Vue are considered better choices for that, because it’s easier to embed them due to their modular nature. But Angular can be used as only a part of a page as well with some adjustments.
First, assuming that we have running Rails app, let’s create angular app inside project dir with:
cd rails-project
ng new angular-app
This will create Angular app, then let’s try to build it with:
cd angular-app
ng build
This will create a ‘dist’ directory inside Angular app’s dir with index.html as main page for the project with embedded scripts, styles inside ‘head’ tag and other HTML tags.
Since we are going to embed Angular into existing page and we don’t need tags like <head>, let’s go into ‘angular-app/src/index.html’ and remove everything except:
<app-root></app-root>
After we build again with ‘ng build’, index.html in our output ‘dist’ dir will contain only links for compiled JS, CSS and ‘<app-root>’ tag.
But because scripts will be generated inside ‘rails-project/angular-project/dist’, they won’t be accessible from the browser, so we need them to be compiled into the ‘rails-project/public’ dir, which is a place where Rails usually puts compiled assets.
To do that let’s go into ‘angular-project/angular.json’ and change ‘outputPath’ to ‘../public/angular-app’ and add ‘deployUrl’: ‘/angular-app/’ under the ‘options’ on same level as ‘outputPath’. First one will specify dir, where compiled assets and html will be stored, second one will set correct paths inside <script> and other tags. Example:
"projects": {
"angular-project": {
"projectType": "application",
"schematics": {},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"deployUrl": "/angular-project/",
"outputPath": "../public/angular-project",
Now, when we build an Angular app, it will be built in ‘/rails-project/public/angular-project/’ and will be available from the browser.
Now, to render it as a part of Rails view, all we need is to place this inside erb file:
<%= render file: “#{Rails.root}/public/angular-app/index.html” %>
If we also want to be able to use Angular Live development server, we will need run ‘ng serve’ to start it and then manually replace generated scripts paths in our index.html to point to the host and port Angular is using.
For example:
<script src=”http://localhost:4200/angular-project/runtime.js" defer>
This way, our compiled page will be using sources from the Live development server, however, if we run ‘ng build’ again, the page will be overridden.