ASP.NET Core, Angular 2 CRUD With Animation Using Template Pack, WEB API And EF 1.0.1


Introduction

In this article, let’s see how to create an ASP.NET Core CRUD Web Application with Angular 2 animation, using Template Pack, Web API, and EF 1.0.1.

Note

Kindly read my previous articles, which explain in-depth about getting started with ASP.NET Core Template Pack.

In this article, we will see the following.

Creating CRUD web Application using ASP.NET Core and Angular 2

  • C: (Create): Insert new Student Details into the database using ASP.NET Core, EF and Web API.
  • R: (Read): Select Student Details from the database using ASP.NET Core, EF and Web API.
  • U: (Update): Update Student Details to the database using ASP.NET Core, EF and Web API
  • D: (Delete): Delete Student Details from the database using ASP.NET Core, EF and Web API.

We will be using Web API to perform our CRUD operations. Web API has the following four methods as Get/Post/Put and Delete, where

  • Get is to request for the data. (Select)
  • Post is to create a data. (Insert)
  • Put is to update the data. (Update)
  • Delete is to delete data. (Delete)

Presenting our CRUD Application, which is more rich with simple Angular2 animations, as shown below.

  • Angular2 Animation for Fade-in elements and controls.
  • Angular2 Animation for move elements and controls from left.
  • Angular2 Animation for move elements and controls from right.
  • Angular2 Animation for move elements and controls from top.
  • Angular2 Animation for move elements and controls from bottom.
  • Angular2 Animation to enlarge button on click.
 

For creating our ASP.NET Core, Angular 2 CRUD with animation, we will be

  • Creating sample database and table in SQL Server to display in our Web Application.
  • Creating ASP.NET Core Angular 2 Starter Application (.NET Core), using Template Pack.
  • Creating EF, DBContext Class and Model class.
  • Creating WEB API for Get/Post/Put and Delete.
  • Creating First Component TypeScript file to get WEB API JSON result, using Http module for Get/Post/Put and Delete method.
  • Creating our first component HTML file for our animation and CRUD Web Application. 

Prerequisites

Make sure, you have installed all the prerequisites in your computer. If not, then download and install all, one by one.

  1. First, download and install Visual Studio 2015 with Update 3 from this link.
  2. If you have Visual Studio 2015 and not yet updated with update 3, download and install Visual Studio 2015 Update 3 from this link
  3. Download and install .NET Core 1.0.1. 
  4. Download and install TypeScript 2.0. 
  5. Download and install Node.js v4.0 or above. I have installed V6.9.1 (download link).
  6. Download ASP.NET Core Template Pack and install iy, which is a file from this link

Code part

Step 1 - Create a database and a table

We will be using our SQL Server database for our WEB API and EF. First, we create a database named StudentsDB and a table as StudentMaster. Here is the SQL script to create a database table and sample record insert query in our table. Run the query given below in your local SQL Server to create a database and a table to be used in our project. 
  1. USE MASTER     
  2. GO     
  3.      
  4. -- 1) Check for the Database Exists .If the database is exist then drop and create new DB     
  5. IF EXISTS (SELECT [nameFROM sys.databases WHERE [name] = 'StudentsDB' )     
  6. DROP DATABASE StudentsDB     
  7. GO     
  8.      
  9. CREATE DATABASE StudentsDB     
  10. GO     
  11.      
  12. USE StudentsDB     
  13. GO     
  14.      
  15.      
  16. -- 1) //////////// StudentMasters     
  17.      
  18. IF EXISTS ( SELECT [nameFROM sys.tables WHERE [name] = 'StudentMasters' )     
  19. DROP TABLE StudentMasters     
  20. GO     
  21.      
  22. CREATE TABLE [dbo].[StudentMasters](     
  23.         [StdID] INT IDENTITY PRIMARY KEY,     
  24.         [StdName] [varchar](100) NOT NULL,        
  25.         [Email]  [varchar](100) NOT NULL,        
  26.         [Phone]  [varchar](20) NOT NULL,        
  27.         [Address]  [varchar](200) NOT NULL     
  28. )     
  29.      
  30. -- insert sample data to Student Master table     
  31. INSERT INTO [StudentMasters]   ([StdName],[Email],[Phone],[Address])     
  32.      VALUES ('Shanu','[email protected]','01030550007','Madurai,India')     
  33.      
  34. INSERT INTO [StudentMasters]   ([StdName],[Email],[Phone],[Address])     
  35.      VALUES ('Afraz','[email protected]','01030550006','Madurai,India')     
  36.           
  37. INSERT INTO [StudentMasters]   ([StdName],[Email],[Phone],[Address])     
  38.      VALUES ('Afreen','[email protected]','01030550005','Madurai,India')     
  39.           
  40.           
  41.      select * from [StudentMasters]     

Step 2 - Create ASP.NET Core Angular 2 Application

After installing all the prerequisites listed above and ASP.NET Core Template, click Start >> Programs >> Visual Studio 2015 >> Visual Studio 2015 on your desktop. Click New >> Project. Select Web >> ASP.NET Core Angular 2 Starter. Enter your project name and click OK.


After creating ASP.NET Core Angular 2 Application, wait for few seconds. You will see that all the dependencies are automatically restored.

 

What is new in ASP.NET Core Template Pack solution?




WWWroot

We can see that all the CSS,JS files are added in “dist” folder .”main-client.js” file is an important file as all the Angular 2 results will be compiled and loaded from this “JS” file to our HTML file.



ClientApp folder

We can see a new folder ClientApp inside our project solution. This folder contains all Angular 2 related Applications like modules, components etc. We can add all our Angular 2 related modules, components, template HTML files, which are all under this folder. We can see in the details about how to create our own Angular 2 Application here as shown below in our article.

In Components folder, under app folder, we can see many subfolders like app. counter, fetchdata, home, and navmenu. By default, this sample application has been created and when we run our application, we can see all the sample results.  


When we run the application, we can see that the left side has navigation and the right side contains the data. All Angular 2 samples will be loaded from the above folder.


Controllers folder

This is our MVC Controller folder. We can create both MVC and Web API Controller in this folder.

View folder

This is our MVC View folder.

Other Important files

We can also see other important ASP.NET Core filessuch as:

project.json

ASP.NET Core dependency list can be found in this file. We will be adding our Entity Framework in the dependency section of this file.

package.json

This is another important file as all Angular 2 related dependency lists will be added here by default. All Angular 2 related dependencies have been added in ASP.NET Core Template Pack.

appsettings.json

We can add our database connection string in this appsetting.json file. We will be using all this in our project to create, build and run our Angular 2 with ASP.NET Core Template Pack, WEB API and EF 1.0.1.

Step 3 - Creating Entity Freamework

Add Entity Framework Packages

To add our Entity Framework Packages in our ASP.NET Core Application, open Project.JSON File and in dependencies, add the line given below to it.

Note

Here, we have used EF version 1.0.1. 

  1. "Microsoft.EntityFrameworkCore.SqlServer""1.0.1","Microsoft.EntityFrameworkCore.Tools""1.0.0-preview2-final"  

When we save the project.json file, we can see the reference has been restored.

 

After a few seconds, we can see Entity Framework package has been restored and all references have been added.

 

Adding connection string

To add the connection string with our SQL connection, open the “appsettings.json” file .Yes this is a JSON file and this file looks as shown below.


In this appsettings.json file, I have added the connection string  

  1. "ConnectionStrings": {  
  2.   
  3.     "DefaultConnection""Server=YOURDBSERVER;Database=StudentsDB;user id=SQLID;password=SQLPWD;Trusted_Connection=True;MultipleActiveResultSets=true;"  
  4.   
  5.   },   

Note- Change SQL connection string, as per your local connection.


Next step is to create a folder named Data to create our model and DBContext class.

 

Creating Model class for Student

We can create a model by adding a new class file in our Data folder. Right Click Data folder and click Add>Click Class. Enter the class name as StudentMasters and click Add.


Now, in this class, we first create a property variable, add student. We will be using this in our WEB API controller.  

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using System.ComponentModel.DataAnnotations;  
  6.   
  7. namespace Angular2ASPCORE.Data  
  8. {  
  9.     public class StudentMasters  
  10.     {  
  11.         [Key]  
  12.         public int StdID { get; set; }  
  13.   
  14.         [Required]  
  15.         [Display(Name = "Name")]  
  16.         public string StdName { get; set; }  
  17.   
  18.         [Required]  
  19.         [Display(Name = "Email")]  
  20.         public string Email { get; set; }  
  21.   
  22.         [Required]  
  23.         [Display(Name = "Phone")]  
  24.         public string Phone { get; set; }  
  25.   
  26.         public string Address { get; set; }  
  27.     }  
  28. }   

Creating Database Context

DBContext is Entity Framework class to establish a connection to the database

We can create a DBContext class by adding a new class file in our Data folder. Right click Data folder and click Add>Click Class. Enter the class name as StudentContext and click Add.


In this class, we inherit DbContext and created Dbset for our students table. 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.EntityFrameworkCore;  
  6.   
  7. namespace Angular2ASPCORE.Data  
  8. {  
  9.     public class studentContext:DbContext  
  10.     {  
  11.         public studentContext(DbContextOptions<studentContext> options)  
  12.             :base(options) { }  
  13.         public studentContext() { }  
  14.         public DbSet<StudentMasters> StudentMasters { get; set; }  
  15.     }  
  16. }  

Startup.CS

Now, we need to add our database connection string and provider as SQL SERVER. To add this, we add the code given below in Startup.cs file under ConfigureServices method. 

  1. // Add Entity framework .  
  2.  services.AddDbContext<studentContext>(options =>options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));  

Step 4 - Creating Web API for CRUD operation

To create our WEB API Controller, right click Controllers folder. Click Add and click New Item.

 

Click ASP.NET in right side. Click Web API Controller class. Enter the name as “StudentMastersAPI.cs” and click Add.


As we all know, Web API is a simple and easy way to build HTTP Services for the Browsers and Mobiles.

Web API has four methods given below as Get/Post/Put and Delete.

  • Get is to request for the data. (Select)
  • Post is to create a data. (Insert)
  • Put is to update the data.
  • Delete is to delete data.

Get Method(Select Operation)

Get Method is to request single item or list of items from our selected database. Here, we will get all student information from StudentMasters table.              

  1. [HttpGet]  
  2.         [Route("Student")]  
  3.         public IEnumerable<StudentMasters> GetStudentMasters()  
  4.         {  
  5.             return _context.StudentMasters;  
  6.   
  7.         }   

Post Method (Insert Operation)

Post Method will be used to insert the data to our database. In Post Method, we will also check if StudentID is already created and return the message. We will pass all Student Master Column parameters to be inserted in to the Student Master table. 

  1. // POST: api/StudentMastersAPI  
  2.         [HttpPost]  
  3.         public async Task<IActionResult> PostStudentMasters([FromBody] StudentMasters studentMasters)  
  4.         {  
  5.             if (!ModelState.IsValid)  
  6.             {  
  7.                 return BadRequest(ModelState);  
  8.             }  
  9.   
  10.             _context.StudentMasters.Add(studentMasters);  
  11.             try  
  12.             {  
  13.                 await _context.SaveChangesAsync();  
  14.             }  
  15.             catch (DbUpdateException)  
  16.             {  
  17.                 if (StudentMastersExists(studentMasters.StdID))  
  18.                 {  
  19.                     return new StatusCodeResult(StatusCodes.Status409Conflict);  
  20.                 }  
  21.                 else  
  22.                 {  
  23.                     throw;  
  24.                 }  
  25.             }  
  26.   
  27.             return CreatedAtAction("GetStudentMasters"new { id = studentMasters.StdID }, studentMasters);  
  28.         }  
  29.         private bool StudentMastersExists(int id)  
  30.         {  
  31.             return _context.StudentMasters.Any(e => e.StdID == id);  
  32.         }   

Put Method (Update Operation)

Put Method will be used to update the selected student data to our database. In Put Method, we will pass StudentID along with all other parameters for update.We pass the StudentID to update the StudentMaster Table by StudentID. 

  1. // PUT: api/StudentMastersAPI/5  
  2.         [HttpPut("{id}")]  
  3.         public async Task<IActionResult> PutStudentMasters([FromRoute] int id, [FromBody] StudentMasters studentMasters)  
  4.         {  
  5.             if (!ModelState.IsValid)  
  6.             {  
  7.                 return BadRequest(ModelState);  
  8.             }  
  9.   
  10.             if (id != studentMasters.StdID)  
  11.             {  
  12.                 return BadRequest();  
  13.             }  
  14.   
  15.             _context.Entry(studentMasters).State = EntityState.Modified;  
  16.   
  17.             try  
  18.             {  
  19.                 await _context.SaveChangesAsync();  
  20.             }  
  21.             catch (DbUpdateConcurrencyException)  
  22.             {  
  23.                 if (!StudentMastersExists(id))  
  24.                 {  
  25.                     return NotFound();  
  26.                 }  
  27.                 else  
  28.                 {  
  29.                     throw;  
  30.                 }  
  31.             }  
  32.   
  33.             return NoContent();  
  34.         }   

Delete Method (Delete Operation)

Delete Method will be used to delete the selected student data from our database. In Delete Method, we will pass StudentID to delete the record.

  1. // DELETE: api/StudentMastersAPI/5  
  2.         [HttpDelete("{id}")]  
  3.         public async Task<IActionResult> DeleteStudentMasters([FromRoute] int id)  
  4.         {  
  5.             if (!ModelState.IsValid)  
  6.             {  
  7.                 return BadRequest(ModelState);  
  8.             }  
  9.   
  10.             StudentMasters studentMasters = await _context.StudentMasters.SingleOrDefaultAsync(m => m.StdID == id);  
  11.             if (studentMasters == null)  
  12.             {  
  13.                 return NotFound();  
  14.             }  
  15.   
  16.             _context.StudentMasters.Remove(studentMasters);  
  17.             await _context.SaveChangesAsync();  
  18.   
  19.             return Ok(studentMasters);  
  20.         }   

To test Get Method, we can run our project and copy the GET method API path. Here, we can see our API path to get api/StudentMastersAPI/Student

Run the program and paste API path to test our output.


Working with Angular2

We create all Angular2 related Apps, Modules, Services, Components and HTML templates under ClientApp/App folder.

We create “students” folder under app folder to create our TypeScript and HTML file to display Student details.


Step 5 - Working with Angular 2 animation


Angular animations are all built on top of the standard Web Animations API. Kindly check this reference link, which explains more detail about Angular2 animations at https://angular.io/docs/ts/latest/guide/animations.html

Adding Animation in Web Applications will give a more rich look for our Website. Here, in this application, we will be using Angular2 animation for Fade-in Enlarge controls on click event and move the elements or controls from left, right, top and bottom. 

Angular2 animation in Home Component

Here, we will be adding our animation in our home page. For this, we edit the Home Component to create our Angular2 animation.

Import part

For using the Angular2 animation, we need to first import “trigger, state, style, transition, animate”.

Our import will look as shown below.

  1. import {Component, Input, trigger, state, style, transition, animate, keyframes} from '@angular/core';   

Component part

In component, we need to add animations: [] to perform our animation with triggers.

The trigger is used to connect Component with our HTML Template. For example, it allows you, on creating a simple animation,  to change the color and resize the button on click event. 

For this, we need to first create a trigger with the name “moveBottom”. We will be using this trigger name in our HTML element or control to move from bottom. In this animation, we have used transition ('void => *' which means this animation will be performed during the page load. We have set the amination time for '1s' and in style, we set the 'translateY(-200px), which means we initially set the button location to bottom -200 from the actual location of the button. When the page loads the button will start from -200 Y-axis place and move up to  the actual button location that is 'translateY(0)' 

  1. trigger('moveBottom', [  
  2.             transition('void => *', [  
  3.                 animate('1s', keyframes([  
  4.                     style({ opacity: 0, transform: 'translateY(-200px)', offset: 0 }),  
  5.                     style({ opacity: 1, transform: 'translateY(25px)', offset: .75 }),  
  6.                     style({ opacity: 1, transform: 'translateY(0)', offset: 1 }),  
  7.   
  8.                 ]))  
  9.             ])  
  10.   
  11.         ])   

In HTML template, we will be using this trigger name with @ symbol to perform the animation, as shown below. Here, we have added the animation for div tag. 

  1. <div  [@moveBottom]= ‘moveBottom’>  
  2.         ASP.NET  Angular2  
  3.     </div>   

It is similar to Bottom. We do the rest of animations for left, right, top and Fade-In. Here is the complete code for Home animation component. 

  1. import { Component, Input, trigger,  state,  style,  transition,   animate,    keyframes } from '@angular/core';  
  2.   
  3. @Component({  
  4.     selector: 'home',  
  5.     animations: [    
  6.         trigger('moveBottom', [  
  7.             transition('void => *', [  
  8.                 animate('1s', keyframes([  
  9.                     style({ opacity: 0, transform: 'translateY(-200px)', offset: 0 }),  
  10.                     style({ opacity: 1, transform: 'translateY(25px)', offset: .75 }),  
  11.                     style({ opacity: 1, transform: 'translateY(0)', offset: 1 }),  
  12.   
  13.                 ]))  
  14.             ])  
  15.   
  16.         ]),  
  17.         trigger('moveTop', [  
  18.   
  19.             transition('void => *', [  
  20.                 animate('1s', keyframes([  
  21.                     style({ opacity: 0, transform: 'translateY(+400px)', offset: 0 }),  
  22.                     style({ opacity: 1, transform: 'translateY(25px)', offset: .75 }),  
  23.                     style({ opacity: 1, transform: 'translateY(0)', offset: 1 }),  
  24.   
  25.                 ]))  
  26.             ])  
  27.   
  28.         ]),  
  29.   
  30.         trigger('moveRight', [  
  31.   
  32.             transition('void => *', [  
  33.                 animate('1s', keyframes([  
  34.                     style({ opacity: 0, transform: 'translateX(-400px)', offset: 0 }),  
  35.                     style({ opacity: 1, transform: 'translateX(25px)', offset: .75 }),  
  36.                     style({ opacity: 1, transform: 'translateX(0)', offset: 1 }),  
  37.   
  38.                 ]))  
  39.             ])  
  40.   
  41.         ]),  
  42.         trigger('movelLeft', [  
  43.   
  44.             transition('void => *', [  
  45.                 animate('4s', keyframes([  
  46.                     style({ opacity: 0, transform: 'translateX(+800px)', offset: 0 }),  
  47.                     style({ opacity: 1, transform: 'translateX(150px)', offset: .75 }),  
  48.                     style({ opacity: 1, transform: 'translateX(0)', offset: 1 }),  
  49.   
  50.                 ]))  
  51.             ])  
  52.   
  53.         ]),  
  54.         trigger('fadeIn', [  
  55.   
  56.             transition('void => *', [  
  57.                 animate('3s', keyframes([  
  58.                     style({ opacity: 0, transform: 'translateX(0)', offset: 0 }),  
  59.                     style({ opacity: 1, transform: 'translateX(0)', offset: 1 }),  
  60.                 ]))  
  61.             ])  
  62.         ])  
  63.     ],  
  64.     template: require('./home.component.html')  
  65. })  
  66. export class HomeComponent {  
  67.     myName: string = "Shanu";  
  68. }   

Here is the complete code for Home HTML template. 

  1. <h1 [@fadeIn]='animStatus'>ASP.NET Core,Angular2 CRUD with Animation using Template Pack, WEB API and EF 1.0.1  </h1>  
  2. <div class="column">  
  3.   
  4.   
  5.   
  6.     <div style="background-color:#0094ff;color:#FFFFFF;font-size:xx-large;width:340px;height:50px;text-shadow:  -2px -1px 0px #000,  
  7.          0px -1px 0px #000,  
  8.          1px -1px 0px #000,  
  9.         -2px  0px 0px #000,  
  10.          1px  0px 0px #000,  
  11.         -2px  1px 0px #000,  
  12.          0px  1px 0px #000,  
  13.          1px  1px 0px #000;text-align:center;display:inline-block;  
  14.                               border-color:#a2aabe;border-style:dashed;border-width:2px;" [@moveBottom]='moveBottom'>  
  15.   
  16.         ASP.NET  Angular2  
  17.   
  18.     </div>  
  19.   
  20.     <div style="background-color:#ff00dc;color:#FFFFFF;font-size:xx-large;width:340px;height:50px;text-shadow:  -2px -1px 0px #000,  
  21.          0px -1px 0px #000,  
  22.          1px -1px 0px #000,  
  23.         -2px  0px 0px #000,  
  24.          1px  0px 0px #000,  
  25.         -2px  1px 0px #000,  
  26.          0px  1px 0px #000,  
  27.          1px  1px 0px #000;text-align:center;display:inline-block;  
  28.                               border-color:#a2aabe;border-style:dashed;border-width:2px;" [@moveTop]='moveTop'>  
  29.   
  30.         CRUD  
  31.   
  32.     </div>  
  33.   
  34.     <div style="background-color:#3ab64a;color:#FFFFFF;font-size:xx-large;width:340px;height:50px;text-shadow:  -2px -1px 0px #000,  
  35.          0px -1px 0px #000,  
  36.          1px -1px 0px #000,  
  37.         -2px  0px 0px #000,  
  38.          1px  0px 0px #000,  
  39.         -2px  1px 0px #000,  
  40.          0px  1px 0px #000,  
  41.          1px  1px 0px #000;text-align:center;display:inline-block;  
  42.                               border-color:#a2aabe;border-style:dashed;border-width:2px;" [@moveRight]='moveRight'>  
  43.   
  44.         Animation  
  45.   
  46.     </div>  
  47. </div>  
  48. <div class="column">  
  49.     <h2>Created by : </h2>  
  50.     <div style="background-color:#ff6a00;color:#FFFFFF;font-size:xx-large;width:320px;height:50px;text-shadow:  -2px -1px 0px #000,  
  51.          0px -1px 0px #000,  
  52.          1px -1px 0px #000,  
  53.         -2px  0px 0px #000,  
  54.          1px  0px 0px #000,  
  55.         -2px  1px 0px #000,  
  56.          0px  1px 0px #000,  
  57.          1px  1px 0px #000;text-align:center;  
  58.                               border-color:#a2aabe;border-style:dashed;border-width:2px;" [@movelLeft]='movelLeft'>  
  59.   
  60.         {{myName}}  
  61.   
  62.     </div>  
  63. </div>   

Step 6 - Creating Component TypeScript

Right click on students folder and click on add new Item. Select Client-side from left side and select TypeScript file. Name the file as “students.component.ts” and click Add.

 

In students.component.ts file, we have three parts

  1. import part
  2. Next is component part
  3. Next we have the class for writing our business logics.

First, we import angular files to be used in our component. Here we import http for using http client in our Angular2 component along with Animation.

In Component, we have selector, animation and template. Selector is to give a name for this app and in our HTML file, we use this selector name to be displayed in our HTML page. Animation is used to perform an animation for our Angular2 Applications. As we have seen in our home component, we have used move, left, right, bottom, top and fade-in, we will be using the same animation in our CRUD page.

In template, we give our output HTML file name. Here, we will create on HTML file as “students.component.html”.

Export class is the main class, where we do all our business logic and variable declarations to be used in our component template. In this class, we get API method result, bind the result to the student array and also we will be performing Rest or Post, Put and Delete methods to perform our CRUD operations.  

  1. import {  
  2.     Component, Input, trigger,  
  3.     state,  
  4.     style,  
  5.     transition,  
  6.     animate,  
  7.     keyframes } from '@angular/core';  
  8. import { Http, Response,  Headers, RequestOptions } from '@angular/http';  
  9. import { FormsModule } from '@angular/forms';  
  10.   
  11.   
  12. @Component({  
  13.     selector: 'students'   
  14.    ,  
  15.        
  16.     animations: [  
  17.   
  18.         trigger('buttonReSize', [  
  19.             state('inactive', style({  
  20.                 transform: 'scale(1)',  
  21.                 backgroundColor: '#f83500'  
  22.             })),  
  23.             state('active', style({  
  24.                 transform: 'scale(1.4)',  
  25.                 backgroundColor: '#0094ff'  
  26.             })),  
  27.             transition('inactive => active', animate('100ms ease-in')),  
  28.             transition('active => inactive', animate('100ms ease-out'))  
  29.         ]),  
  30.   
  31.         trigger('moveBottom', [  
  32.   
  33.             transition('void => *', [  
  34.                 animate(900, keyframes([  
  35.                     style({ opacity: 0, transform: 'translateY(-200px)', offset: 0 }),  
  36.                     style({ opacity: 1, transform: 'translateY(25px)', offset: .75 }),  
  37.                     style({ opacity: 1, transform: 'translateY(0)', offset: 1 }),  
  38.                       
  39.                 ]))  
  40.             ])  
  41.   
  42.         ]),  
  43.         trigger('moveTop', [  
  44.   
  45.             transition('void => *', [  
  46.                 animate(900, keyframes([  
  47.                     style({ opacity: 0, transform: 'translateY(+400px)', offset: 0 }),  
  48.                     style({ opacity: 1, transform: 'translateY(25px)', offset: .75 }),  
  49.                     style({ opacity: 1, transform: 'translateY(0)', offset: 1 }),  
  50.   
  51.                 ]))  
  52.             ])  
  53.   
  54.         ]),  
  55.          
  56.         trigger('moveRight', [  
  57.   
  58.             transition('void => *', [  
  59.                 animate(900, keyframes([  
  60.                     style({ opacity: 0, transform: 'translateX(-400px)', offset: 0 }),  
  61.                     style({ opacity: 1, transform: 'translateX(25px)', offset: .75 }),  
  62.                     style({ opacity: 1, transform: 'translateX(0)', offset: 1 }),  
  63.   
  64.                 ]))  
  65.             ])  
  66.   
  67.         ]),  
  68.         trigger('movelLeft', [  
  69.   
  70.             transition('void => *', [  
  71.                 animate(900, keyframes([  
  72.                     style({ opacity: 0, transform: 'translateX(+400px)', offset: 0 }),  
  73.                     style({ opacity: 1, transform: 'translateX(25px)', offset: .75 }),  
  74.                     style({ opacity: 1, transform: 'translateX(0)', offset: 1 }),  
  75.   
  76.                 ]))  
  77.             ])  
  78.   
  79.         ]),  
  80.         trigger('fadeIn', [  
  81.             transition('* => *', [  
  82.                 animate('1s', keyframes([  
  83.                     style({ opacity: 0, transform: 'translateX(0)', offset: 0 }),  
  84.                     style({ opacity: 1, transform: 'translateX(0)', offset: 1 }),  
  85.                 ]))  
  86.             ])  
  87.         ]),  
  88.   
  89.          
  90.     ],  
  91.     template: require('./students.component.html')  
  92. })  
  93.   
  94. export class studentsComponent {  
  95.       // to get the Student Details  
  96.     public student: StudentMasters[] = [];   
  97.     // to hide and Show Insert/Edit   
  98.     AddstudetnsTable: Boolean = false;  
  99.     // To stored Student Informations for insert/Update and Delete  
  100.     public StdIDs = "0";  
  101.     public StdNames  = "";  
  102.     public Emails = "";  
  103.     public Phones = "";  
  104.     public Addresss= "";  
  105.   
  106.     //For display Edit and Delete Images  
  107.     public imgEdit = require("./Images/edit.gif");  
  108.     public imgDelete = require("./Images/delete.gif");  
  109.   
  110.     myName: string;  
  111.     //for animation status   
  112.     animStatus: string = 'inactive';  
  113.     constructor(public http: Http) {  
  114.         this.myName = "Shanu";  
  115.         this.AddstudetnsTable = false;  
  116.         this.getData();  
  117.     }  
  118.   
  119.     //for Animation to toggle Active and Inactive  
  120.     animButton() {  
  121.         this.animStatus = (this.animStatus === 'inactive' ? 'active' : 'inactive');  
  122.     }  
  123.   
  124.     //to get all the Student data from Web API  
  125.     getData()  
  126.     {  
  127.         this.http.get('/api/StudentMastersAPI/Student').subscribe(result => {  
  128.             this.student = result.json();  
  129.         });  
  130.     }  
  131.   
  132.   
  133.     // to show form for add new Student Information  
  134.     AddStudent() {  
  135.         this.animButton();  
  136.         this.AddstudetnsTable = true;   
  137.     this.StdIDs = "0";  
  138.     this.StdNames = "";  
  139.     this.Emails = "";  
  140.     this.Phones = "";  
  141.     this.Addresss = "";  
  142.     }  
  143.   
  144.     // to show form for edit Student Information  
  145.     editStudentsDetails(StdID, StdName, Email, Phone, Address) {  
  146.         this.animButton();  
  147.         this.AddstudetnsTable = true;  
  148.         this.StdIDs = StdID;  
  149.         this.StdNames = StdName;  
  150.         this.Emails = Email;  
  151.         this.Phones = Phone;  
  152.         this.Addresss = Address;  
  153.     }  
  154.   
  155.     // If the studentid is 0 then insert the student infromation using post and if the student id is more than 0 then edit using put mehod  
  156.     addStudentsDetails(StdID, StdName, Email, Phone, Address) {  
  157.         alert(StdName);  
  158.         var headers = new Headers();  
  159.         headers.append('Content-Type''application/json; charset=utf-8');  
  160.         if (StdID == 0)  
  161.         {  
  162.             this.http.post('api/StudentMastersAPI', JSON.stringify({ StdID: StdID, StdName: StdName, Email: Email, Phone: Phone, Address: Address }), { headers: headers }).subscribe();  
  163.             alert("Student Detail Inserted");  
  164.         }  
  165.         else  
  166.         {  
  167.             this.http.put('api/StudentMastersAPI/' + StdID, JSON.stringify({ StdID: StdID, StdName: StdName, Email: Email, Phone: Phone, Address: Address }), { headers: headers }).subscribe();  
  168.             alert("Student Detail Updated");  
  169.         }         
  170.         
  171.         this.AddstudetnsTable = false;   
  172.         this.getData();           
  173.     }  
  174.   
  175.     //to Delete the selected student detail from database.  
  176.     deleteStudentsDetails(StdID) {           
  177.         var headers = new Headers();  
  178.         headers.append('Content-Type''application/json; charset=utf-8');  
  179.          
  180.         this.http.delete('api/StudentMastersAPI/' + StdID, { headers: headers }).subscribe();  
  181.             alert("Student Detail Deleted");  
  182.             this.getData();          
  183.     }  
  184.   
  185.     closeEdits()  
  186.     {  
  187.         this.AddstudetnsTable = false;  
  188.         this.StdIDs = "0";  
  189.         this.StdNames = "";  
  190.         this.Emails = "";  
  191.         this.Phones = "";  
  192.         this.Addresss = "";  
  193.     }  
  194. }  
  195.   
  196. export interface StudentMasters {  
  197.     stdID: number;  
  198.     stdName: string;  
  199.     email: string;  
  200.     phone: string;  
  201.     address: string;  
  202. }   

Step 7 - Creating HTML Template file

Right click on students folder and click on add new Item. Select Client-side from left side, select HTML file, name the file as “students.component.html” and click Add.

 

Write the HTML code given below to bind the result in our HTML page. 

  1. <h1 [@fadeIn]='animStatus'>ASP.NET Core,Angular2 CRUD with Animation using Template Pack, WEB API and EF 1.0.1  </h1>   
  2.  <div class="column">  
  3.   
  4.      <h2>Created by : </h2>  
  5.     <div style="background-color:#ff6a00;color:#FFFFFF;font-size:xx-large;width:260px;height:50px;text-shadow:  -2px -1px 0px #000,  
  6.          0px -1px 0px #000,  
  7.          1px -1px 0px #000,  
  8.         -2px  0px 0px #000,  
  9.          1px  0px 0px #000,  
  10.         -2px  1px 0px #000,  
  11.          0px  1px 0px #000,  
  12.          1px  1px 0px #000;text-align:center;  
  13.                               border-color:#a2aabe;border-style:dashed;border-width:2px;"   [@movelLeft]='animStatus'>  
  14.            
  15.             {{myName}}  
  16.         
  17.     </div>  
  18. </div>  
  19.   
  20.   
  21. <hr style="height: 1px;color: #123455;background-color: #d55500;border: none;color: #d55500;" />  
  22. <p *ngIf="!student"><em>Loading Student Details please Wait ! ...</em></p>  
  23.   
  24. <table id="tblContainer" style='width: 99%;table-layout:fixed;'>  
  25.     <tr>  
  26.         <td>  
  27.             <table style="background-color:#FFFFFF; border: dashed 3px #FFFFFF; padding: 5px;width: 99%;table-layout:fixed;" cellpadding="2"  
  28.                    cellspacing="2">  
  29.                 <tr style="height: 30px;  color:#123455 ;border: solid 1px #659EC7;">  
  30.                     <td width="40px"> </td>  
  31.                     <td width="50%">  
  32.                         <h1> Add New Students Information <strong style="color:#0094ff"> </strong></h1>  
  33.                          
  34.                     </td>  
  35.                     <td align="right">  
  36.                         <button (click)=AddStudent() style="background-color:#f83500;color:#FFFFFF;font-size:large;width:260px;height:50px;  
  37.                               border-color:#a2aabe;border-style:dashed;border-width:2px;" [@moveRight]='animStatus'  [@buttonReSize]='animStatus'>  
  38.                             Add New Studetnt Information  
  39.                         </button>  
  40.                            
  41.                     </td>  
  42.                 </tr>  
  43.             </table>  
  44.   
  45.         </td>  
  46.     </tr>  
  47.     <tr>  
  48.         <td>  
  49.             <hr style="height: 1px;color: #123455;background-color: #d55500;border: none;color: #d55500;" />  
  50.         </td>  
  51.     </tr>  
  52.     <tr *ngIf="AddstudetnsTable">  
  53.         <td  [@fadeIn]='animStatus'>  
  54.             <table>  
  55.                 <tr>  
  56.                     <td>  
  57.   
  58.   
  59.                         <table style="background-color:#FFFFFF; border: dashed 3px #6D7B8D; padding :5px;width :99%;table-layout:fixed;" cellpadding="2" cellspacing="2">  
  60.                             <tr style="height: 30px; background-color:#336699 ; color:#FFFFFF ;border: solid 1px #659EC7;">  
  61.                                 <td width="40">  
  62.                                        
  63.                                 </td>  
  64.                                 <td>  
  65.                                     <h2>Insert/Edit Student Details : </h2>  
  66.                                 </td>  
  67.                             </tr>  
  68.                             <tr>  
  69.                                 <td width="100">  
  70.                                        
  71.                                 </td>  
  72.                                 <td>  
  73.                                     <table style="color:#9F000F;font-size:large; padding :5px;" cellpadding="12" cellspacing="16">  
  74.                                         <tr>  
  75.                                             <td><b>Students ID: </b> </td>  
  76.                                             <td>  
  77.                                                 <input type="text" #StdID (ngModel)="StdIDs" value="{{StdIDs}}" style="background-color:tan" readonly>  
  78.                                             </td>  
  79.                                             <td width="20"> </td>  
  80.                                             <td><b>Students Name: </b> </td>  
  81.                                             <td>  
  82.                                                 <input type="text" #StdName (ngModel)="StdNames" value="{{StdNames}}">  
  83.                                             </td>  
  84.                                             <td></td>  
  85.                                         </tr>  
  86.                                         <tr>  
  87.                                             <td><b>Email: </b> </td>  
  88.                                             <td>  
  89.                                                 <input type="text" #Email (ngModel)="Emails" value="{{Emails}}">  
  90.                                             </td>  
  91.                                             <td width="20"> </td>  
  92.                                             <td><b>Phone: </b> </td>  
  93.                                             <td>  
  94.                                                 <input type="text" #Phone (ngModel)="Phones" value="{{Phones}}">  
  95.                                             </td>  
  96.                                             <td></td>  
  97.                                         </tr>  
  98.                                         <tr>  
  99.                                             <td><b>Address: </b> </td>  
  100.                                             <td  >  
  101.                                                 <input type="text" #Address (ngModel)="Addresss" value="{{Addresss}}">  
  102.   
  103.                                             </td>  
  104.                                             <td width="20"> </td>  
  105.                                             <td align="right" colspan="2">  
  106.                                                 <button (click)=addStudentsDetails(StdID.value,StdName.value,Email.value,Phone.value,Address.value) style="background-color:#428d28;color:#FFFFFF;font-size:large;width:220px;  
  107.                               border-color:#a2aabe;border-style:dashed;border-width:2px;"  [@moveBottom]='animStatus' >  
  108.                                                     Save  
  109.                                                 </button>  
  110.   
  111.                                                
  112.                                                  
  113.                                             </td>  
  114.                                             <td>  
  115.                                                      
  116.                                                 <button (click)=closeEdits() style="background-color:#334668;color:#FFFFFF;font-size:large;width:180px;  
  117.                               border-color:#a2aabe;border-style:dashed;border-width:2px;"  [@moveTop]='animStatus' >  
  118.                                                     Close  
  119.                                                 </button>  
  120.                                             </td>  
  121.                                         </tr>  
  122.                                     </table>  
  123.                                 </td>  
  124.                             </tr>  
  125.   
  126.                         </table>  
  127.                     </td>  
  128.                 </tr>  
  129.                 <tr>  
  130.                     <td colspan="2">  
  131.                         <hr style="height: 1px;color: #123455;background-color: #d55500;border: none;color: #d55500;" />  
  132.                     </td>  
  133.                 </tr>  
  134.             </table>  
  135.         </td>  
  136.   
  137.                 </tr>  
  138.                 <tr>  
  139.                     <td  [@moveBottom]='animStatus' >  
  140.   
  141.   
  142.                         <table class='table' style="background-color:#FFFFFF; border:2px #6D7B8D; padding:5px;width:99%;table-layout:fixed;" cellpadding="2" cellspacing="2" *ngIf="student">  
  143.   
  144.                             <tr style="height: 30px; background-color:#336699 ; color:#FFFFFF ;border: solid 1px #659EC7;">  
  145.                                 <td width="70" align="center">Edit</td>  
  146.                                 <td width="70" align="center">Delete</td>  
  147.                                 <td width="100" align="center">Student ID</td>  
  148.                                 <td width="160" align="center">Student Name</td>  
  149.                                 <td width="160" align="center">Email</td>  
  150.                                 <td width="120" align="center">Phone</td>  
  151.                                 <td width="180" align="center">Address</td>  
  152.   
  153.   
  154.                             </tr>  
  155.                             <tbody *ngFor="let StudentMasters  of student"  [@moveTop]='animStatus'>  
  156.                                 <tr>  
  157.                                     <td align="center" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">  
  158.                                         <span style="color:#9F000F">  
  159.                                             <img src="{{imgEdit}}"  style="height:32px;width:32px" (click)=editStudentsDetails(StudentMasters.stdID,StudentMasters.stdName,StudentMasters.email,StudentMasters.phone,StudentMasters.address)>  
  160.                                         </span>  
  161.   
  162.                                     </td>  
  163.   
  164.                                     <td align="center" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">  
  165.                                         <span style="color:#9F000F">  
  166.                                             <img src="{{imgDelete}}" style="height:32px;width:32px" (click)=deleteStudentsDetails(StudentMasters.stdID)>  
  167.                                         </span>  
  168.   
  169.                                     </td>  
  170.   
  171.                                     <td align="center" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">  
  172.                                         <span style="color:#9F000F">{{StudentMasters.stdID}}</span>  
  173.                                     </td>  
  174.   
  175.                                     <td align="left" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">  
  176.                                         <span style="color:#9F000F">{{StudentMasters.stdName}}</span>  
  177.                                     </td>  
  178.   
  179.                                     <td align="left" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">  
  180.                                         <span style="color:#9F000F">{{StudentMasters.email}}</span>  
  181.                                     </td>  
  182.   
  183.                                     <td align="center" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">  
  184.                                         <span style="color:#9F000F">{{StudentMasters.phone}}</span>  
  185.                                     </td>  
  186.   
  187.                                     <td align="left" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">  
  188.                                         <span style="color:#9F000F">{{StudentMasters.address}}</span>  
  189.                                     </td>  
  190.                                 </tr>  
  191.                             </tbody>  
  192.                         </table>  
  193.                     </td>  
  194.                 </tr>  
  195.             </table>   

Step 8 - Adding Student Navigation menu

We can add our newly created student details menu in the existing menu.

To add our new navigation menu, open the “navmenu.component.html” under navmenu menu. Write the code given below to add our navigation menu link for the students. 

  1. <li [routerLinkActive]="['link-active']">  
  2.                     <a [routerLink]="['/students']">  
  3.                         <span class='glyphicon glyphicon-th-list'></span> Students  
  4.                     </a>  
  5.                 </li>   

Step 9 - App Module

App Module is a root for all the files and we can find the app.module.ts under ClientApp\ app. 

  1. Import our students component  
  2. import { studentsComponent } from './components/students/students.component';   

Next in @NGModule add studentsComponent

In routing, add your students path.

The code will look, as shown below. 

  1. import { NgModule } from '@angular/core';  
  2. import { RouterModule } from '@angular/router';  
  3. import { UniversalModule } from 'angular2-universal';  
  4. import { AppComponent } from './components/app/app.component'  
  5. import { NavMenuComponent } from './components/navmenu/navmenu.component';  
  6. import { HomeComponent } from './components/home/home.component';  
  7. import { FetchDataComponent } from './components/fetchdata/fetchdata.component';  
  8. import { CounterComponent } from './components/counter/counter.component';  
  9. import { studentsComponent } from './components/students/students.component';  
  10.   
  11. @NgModule({  
  12.     bootstrap: [ AppComponent ],  
  13.     declarations: [  
  14.         AppComponent,  
  15.         NavMenuComponent,  
  16.         CounterComponent,  
  17.         FetchDataComponent,  
  18.         HomeComponent,  
  19.         studentsComponent  
  20.     ],  
  21.     imports: [  
  22.         UniversalModule, // Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too.  
  23.         RouterModule.forRoot([  
  24.             { path: '', redirectTo: 'home', pathMatch: 'full' },  
  25.             { path: 'home', component: HomeComponent },  
  26.             { path: 'counter', component: CounterComponent },  
  27.             { path: 'fetch-data', component: FetchDataComponent },  
  28.             { path: 'students', component: studentsComponent },   
  29.             { path: '**', redirectTo: 'home' }  
  30.         ])  
  31.     ]  
  32. })  
  33. export class AppModule {  
  34. }   

Step 10 - Build and run the application

Build and run the application and you can see the Home page with animation and Student CRUD page animation.

 

Note

First, create a database and table in your SQL Server. You can run SQL Script. With the help of this article, you have learned to create StudentsDB database and StudentMasters table. Don’t forget to change the connection string from “appsettings.json”.

Up Next
    Ebook Download
    View all
    Learn
    View all