But Microsoft team has allowed us to write Angular code in Visual Studio and it works very well with the back-end code of .Net.
Let us see how to create the Angular application using new templates which have been introduced with .Net Core 2.0. For more information have a look here.
First of all click on File -> New -> Project. It will open below window:
Then click on .Net Core Web application, it will open below window:
Click on the Angular template which will create a brand new project of Angular in which:
- Views of MVC will be replaced by Angular
- We still have Models and Controllers
The structure of the project would look like as below:
As you can see we have Controllers here but currently we do not have any models but they can be added when we plug the database with the application.
Let us look at how the Views look like, For that, we will open Index.cshtml which looks like below:
This is just the bootstrapper of Angular and we are not going to write any views or Angular code into this folder for the current project.
Now let us look at the actual client side of the application where we can find all the TypeScript.
What is TypeScript?
For our example we have created the CounterComponent which is used to increment the counter once we click on a button and FetchDataComponent which fetches the data from the API and shows it in the view as shown below:
Let us look at CounterComponent first
In Counter.component.ts file we will write below code:
Here you can see the Angular code but it is written in the TypeScript. Like we have currentCount variable in above component which will be bound in the respected HTML file as below:
Once the code is written, just click on IIS Express button on top of the page and it will run the Angular application:
So CurrentCount will be increased once we click on Increment button:
Now let us look at FetchDataComponent.
Here in FetchData.Component.ts file we can write the code to call the API which will return the data as shown below:
The API endpoint resides in the Controller folder as shown below:
WeatherForecasts method returns the json data and then Angular processes that, repopulate the web page with the appropriate HTML as shown below:
When we run the application, TypeScript would be running in the background. So if you make any changes in the code, it would be reflected automatically in the browser.
It is possible because Microsoft team has created a Node services so that:
- We can return the value in C# code which we can utilize.
For example, we can kickoff WebPack from C# code so whenever we click on Save button:
- There is a watch in the background which picks up the save
- Node.js is running in Background which recreates the View
- Sends back the view to the browser
Hope it helps.