Adding Angular2 to MEAN App
This post to use Angular2 in combination with Node.js is technically 4th post after Part 1 and Part 2 of Restful API Sample app and usage of MongoDB related posts written previously .
Install Angular CLI if its not already installed.
# npm install -g angular-cli
Now, we are to create Angular2 within the Node App that we are already creating. Go the project home directory and create the Angular home directory. I call it angular-src:
#ng new angular-src
It will install angular project within the main project. Go to ‘angular-src’ directory and open file: angular-cli.json
We would like to change the destination directory for the files to be distributed. So, change value for ‘outDir’ to ‘public’
Now, using CLI, apart from starting ‘node server’ we have to run the ‘angular server’ too. Browse to ‘angular-src’ directory using new command-line window and use following command:
# ng serve
it should start listening at port 4200. Please check the logs of CLI to confirm the port, if you get a different port based on your own environment settings, that is not a big deal.
Now go to browser, http://localhost:4200 to see if there is text like ‘app works‘, it means Angular2 setup is successful.
There is an app folder withing ‘angular-src/src’ folder. Most of the work is in this folder.
app.module.ts has most of the import stuff
Now is the time to add components to the app: For my app, I have divided components like header, contentarea, blocks, footer etc. Following command in CLI inside ‘angular-src’ directory helps to create components and their standard associations.
#ng g component COMPONENT_NAME
replace string ‘COMPONENT_NAME‘ with your component names. This will create the component folder in angular-src/src/app and will create basic files in there. It will also add the component declaration in app.modules.ts file
After creating all the components required for now using above command, Lets display Header and Footer within the main file.
For this purpose, within ‘app.component.html‘ add following tags to add Header and footer. It is not compulsory to do it like this. You may have your own structure as per requirements of your project.
Now is the time to populate the Home Page with data we saved in last post using MongoDB connection. We will cover that in next post along with some basic UI.