How to Create your First Angular Application with .NET Core in Visual Studio?

In this article, I have explained about how to create your first angular application with ASP.NET Core Web application in Visual Studio 2017 with default angular template, also explained about to create new components. Angular application can be used to develop Single Page Application (SPA).

Follow the below steps to start creating on angular application.

Step 1: File -> New -> Project

Step 2: Select Web -> ASP.NET Core Web Application. Enter the Project Name. Here I have named as “MyFirstAngularApp”. Click OK.

Step 3: Chose the .NET Core version, under which you want to create Angular Application. Here I have chosen Core 2.2.  Select Angular Template as shown in below screenshot. Click OK.

Note: Make sure .NET Core 2.2 SDK already installed to your machine. If not, you can install this using the below download link.

64 Bit: https://dotnet.microsoft.com/download/thank-you/dotnet-sdk-2.2.108-windows-x64-installer

32 Bit: https://dotnet.microsoft.com/download/thank-you/dotnet-sdk-2.2.108-windows-x86-installer

To Use higher version like Core 3.0, you need to use Visual Studio 2019.

Step 4: That’s it. You have done the creation of your First Angular Application with .Net Core 2.2 in Visual Studio 2017.

Step 5: Check the Solution Explorer. All project related files are created with default configuration required for Angular. Build the application. While building/running the application as first time, it takes time to download and install some required npm packages.

Note: If you don’t install Node.js. You need to install it to run the Angular application. To install the Node.js, download the recommended installer from this link https://nodejs.org/en/ , then install into your machine.

Step 6: After successful build, run the application, you will get the following output in browser,

How to Create New Components in the Angular Application?

Here, I have explained the steps to add new components in Angular application which you have created by following the above steps.

Take an example to add new component, this will display the full name of user by getting first name and last name as input.

Step 1: Navigate to ClientApp -> src -> app. Create new folder under named as “users”. You find other components like counter, fetch-data, home nav-menu which created in predefined angular templates. Refer the below image,

Step 2: Create 3 new files under the users folder.

  1. user.component.html
  2. user.component.ts
  3. user.component.css

To create new file, Right click on users folder -> Add -> New Item.

Select the HTML page template and give the name as “user.component.html”. Click OK.

This will create the new file “users.component.html” under user folder. Follow the same step two create other two files, but you should select TypeScript file template and Stylesheet template to create “user.component.ts” file and user.component.css file respectively.

After you created, all three files, the solution explorer will be like this.

Step 3:  Write the below code in user.component.ts file.

import { Component } from '@angular/core';

@Component({
  selector: 'users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css']
})
export class UsersComponent {
}

Write user component HTML code in user.component.html file.

<h1>Display User's Full Name</h1><br />
<div>
  <div class="row">
    <div class="col-sm-2">
      <label>First Name: </label>
    </div>
    <div class="col-sm-6">
      <input type="text" placeholder="Enter First Name">
    </div>
  </div>
  <br />
  <div class="row">
    <div class="col-sm-2">
      <label>Last Name: </label>
    </div>
    <div class="col-sm-6">
      <input type="text" placeholder="Enter Last Name">
    </div>
  </div>
  <br />
  <div class="row">
    <div class="col-sm-2">
      <label>Full Name: </label>
    </div>
    <div class="col-sm-6">
    </div>
  </div>
  <br />
  <div class="row">
    <div class="col-sm-6">
      <button type="button" class="btn btn-primary">Display Full Name</button>
    </div>
  </div>
</div>  

You can write any on styles user component HTML code in user.component.css file. Here I don’t write any styles. So, left this file as empty.

Step 4: Need to add below code in app.module.ts file which located under ClientApp -> src.

a. Import the users component.

b. Add the declaration part under @NgModule.

c. Add the routing to this component page.

Final Code of app.module.ts file will be like below,

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { RouterModule } from '@angular/router';

import { AppComponent } from './app.component';
import { NavMenuComponent } from './nav-menu/nav-menu.component';
import { HomeComponent } from './home/home.component';
import { CounterComponent } from './counter/counter.component';
import { FetchDataComponent } from './fetch-data/fetch-data.component';
import { UsersComponent } from './users/user.component';

@NgModule({
  declarations: [
    AppComponent,
    NavMenuComponent,
    HomeComponent,
    CounterComponent,
    FetchDataComponent,
    UsersComponent
  ],
  imports: [
    BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
    HttpClientModule,
    FormsModule,
    RouterModule.forRoot([
      { path: '', component: HomeComponent, pathMatch: 'full' },
      { path: 'counter', component: CounterComponent },
      { path: 'fetch-data', component: FetchDataComponent },
      { path: 'display-users', component: UsersComponent }
    ])
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 5: Add user component link in navigation menu. This code can be added in nav-menu.component.html file.

<li class="nav-item" [routerLinkActive]='["link-active"]'>
  <a class="nav-link text-dark" [routerLink]='["/display-users"]'>Users</a>
</li>

Step 6: Now build and run the application. You can see new link “Users” added in menu. Click on this open the user page.

Step 7: Now we can do data binding to get the input from text boxes and write business logic to combine the input and show the result in View.

a.  First, we need to define the property and function in user.component.ts file inside the UsersComponent Class which we already created like below,

export class UsersComponent {
  firstName: string;
  lastName: string;
  fullName: string;

  FindFullName() {
    this.fullName = this.firstName + this.lastName;
  }
} 

Here defined 3 properties, and one method.

b. Then bind these properties and method to user.component.html file,

[(ngModel)] – used to bind the property to input textbox. Here firstName and lastName properties has been bind to first two input text boxes respectively.

<input [(ngModel)]="firstName" type="text" placeholder="Enter First Name">

{{propertyName}} – used to display the value of property. Here value assigned to fullName property is showed.

<label>{{fullName}}</label>

(event) –  used to trigger the event. Here (click) event is triggered, which will call the function.

<button type="button" (click)="FindFullName()" class="btn btn-primary">Display Full Name</button>

Find the HTML code after done the property binding,

<h1>Display User's Full Name</h1><br />
<div>
  <div class="row">
    <div class="col-sm-2">
      <label>First Name: </label>
    </div>
    <div class="col-sm-6">
      <input [(ngModel)]="firstName" type="text" placeholder="Enter First Name">
    </div>
  </div>
  <br />
  <div class="row">
    <div class="col-sm-2">
      <label>Last Name: </label>
    </div>
    <div class="col-sm-6">
      <input [(ngModel)]="lastName" type="text" placeholder="Enter Last Name">
    </div>
  </div>
  <br />
  <div class="row">
    <div class="col-sm-2">
      <label>Full Name: </label>
    </div>
    <div class="col-sm-6">
      <label>{{fullName}}</label>
    </div>
  </div>
  <br />
  <div class="row">
    <div class="col-sm-6">
      <button type="button" (click)="FindFullName()" class="btn btn-primary">Display Full Name</button>
    </div>
  </div>
</div>

Step 8: Now Run the application, Give First Name and Last Name, click on Display Full Name button, this will show the Full Name.

How to Bind Data from API to Components in the Angular Application?

Step 1: Create new API Controller, here I have created new API controller named “CustomerDataController”.

Step 2: New API controller will be created with some default get and post method. You can delete all the methods inside the controller class.

Create new HttpGet action method which will be used to write the business logic to get all the customer data from any data source.  Here for example, I have initialized some local data using list object. You can modify this to get the data from Database.

Find the complete code in API Controller,

namespace MyFirstAngularApp.Controllers
{
    [Route("api/[controller]")]
    public class CustomerDataController : Controller
    {
        [HttpGet("[action]")]
        public IEnumerable<Customer> GetCustomerData()
        {
            Customer customers = new Customer();
            return customers.GetCustomer();
        }
    }

    public class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }

        List<Customer> CustomerList = new List<Customer>();

        public Customer() { }

        public List<Customer> GetCustomer()
        {
            //Initialize 10 dummy customer id's and names. 
            for (int count = 1; count <= 10; count++)
            {
                Customer customerData = new Customer()
                {
                    Id = count,
                    Name = "Name " + count
                };
                CustomerList.Add(customerData);
            }
            return this.CustomerList;
        }
    }
}

Step 3: We should create new component using the steps which i already mentioned above. Created new components like below,

Step 4: Write a code to import the component and call the API get action method in customer.component.ts file.

import { Component, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'customer',
  templateUrl: './customer.component.html',
  styleUrls: ['./customer.component.css']
})

export class CustomerComponent {
  public customerList: Customer[];
  //To call API  
  constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
    http.get<Customer[]>(baseUrl + 'api/CustomerData/GetCustomerData').subscribe(result => {
      this.customerList = result;
    }, error => console.error(error));
  }
}

interface Customer {
  id: number;
  name: string;
}

Step 5: Write the HTML code block to show the customer data in customer.component.html file.

<h1>Customer Details</h1>

<table class='table' *ngIf= "customerList">
  <thead>
    <tr>
      <th>Id</th>
      <th>Name</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let customer of customerList">
      <td>{{ customer.id}}</td>
      <td>{{ customer.name }}</td>
    </tr>
  </tbody>
</table>  

Here *ngIf performs same as if condition. *ngIf = “customerList” – this check customerList has count > 0 and not null or empty, then only render the table.

*ngFor – Performs same as for loop statement. *ngFor=”let customer of customerList” – this will render the tr tag in loop till customerList count.

Step 6: Write your CSS styles in customer.component.css file.

Step 7: That’s it, you have completed the code make the HTTP Get API call, which will collect the data from datasource, and this data will again bind to view. Build and Run the application.

Step 8: Refer the Output screenshot,

Advertisements

Leave a Reply