Before moving ahead, I would recommend you read my previous articles which explain how to install npm and add other mandatory files.
Getting Started
- Start Visual Studio.
- Create a new website.
- Provide the name and the location of the website.
- Click "Next".
After adding all mandatory Angular 2 files like systemjs.config.js, tsconfig.json and node_modules, here is my systemjs.config.js.
-
-
-
-
- (function(global) {
- System.config({
- paths: {
-
- 'npm:': 'node_modules/'
- },
-
- map: {
-
- app: '/app',
-
- '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
- '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
- '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
- '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
- '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
- '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
- '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
- '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
-
- 'rxjs': 'npm:rxjs',
- 'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',
- 'ng2-bs3-modal': 'npm:/ng2-bs3-modal'
- },
-
- packages: {
- app: {
- main: 'main.js',
- defaultExtension: 'js'
- },
- rxjs: {
- defaultExtension: 'js'
- },
- 'ng2-bs3-modal': {
- main: '/bundles/ng2-bs3-modal.js',
- defaultExtension: 'js'
- }
- }
- });
- })(this);
In this file, you can change your app folder name or path and you can change node_modules path.
tsconfig.json
- {
- "compilerOptions": {
- "target": "es5",
- "module": "commonjs",
- "moduleResolution": "node",
- "sourceMap": true,
- "emitDecoratorMetadata": true,
- "experimentalDecorators": true,
- "lib": ["es2015", "dom"],
- "noImplicitAny": false,
- "suppressImplicitAnyIndexErrors": true
- }
- }
First of all, add a new item using right-click on solutions and go to data tab and select ADO.NET Entity Data Model. Here is my entity model diagram.
Now, add a new Web API Controller in controller folder like this.
Now, add Web API code.
- public class AlbumAPIController: BaseAPIController {
-
- public HttpResponseMessage Get() {
- return ToJson(MusicStoreDB.Albums.AsEnumerable());
- }
-
- public HttpResponseMessage Post([FromBody] Album value) {
- MusicStoreDB.Albums.Add(value);
- return ToJson(MusicStoreDB.SaveChanges());
- }
-
- public HttpResponseMessage Put(int id, [FromBody] Album value) {
- MusicStoreDB.Entry(value).State = EntityState.Modified;
- return ToJson(MusicStoreDB.SaveChanges());
- }
-
- public HttpResponseMessage Delete(int id) {
- MusicStoreDB.Albums.Remove(MusicStoreDB.Albums.FirstOrDefault(x => x.AlbumId == id));
- return ToJson(MusicStoreDB.SaveChanges());
- }
- }
In my Web API, as you can see, I am inheriting by BaseAPIController. Here is the code for that.
- public class BaseAPIController: ApiController {
- protected readonly MVCMUSICSTOREEntities MusicStoreDB = new MVCMUSICSTOREEntities();
- protected HttpResponseMessage ToJson(dynamic obj) {
- var response = Request.CreateResponse(HttpStatusCode.OK);
- response.Content = new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json");
- return response;
- }
- }
BaseAPI is a new API which converts result in JSON format.
If you are not working on an MVC project, then add a new class in App_Start folder.
- public static class WebApiConfig {
- public static void Register(HttpConfiguration config) {
-
-
- config.MapHttpAttributeRoutes();
- config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/octet-stream"));
- config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new {
- id = RouteParameter.Optional
- });
- }
- }
And register in Global.asax.
- AreaRegistration.RegisterAllAreas();
- GlobalConfiguration.Configure(WebApiConfig.Register);
- FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
- RouteConfig.RegisterRoutes(RouteTable.Routes);
- BundleConfig.RegisterBundles(BundleTable.Bundles);
Now, let’s move to the app folder where we have all Angular files like module, routing, main, components, HTML, style sheets etc.
First of all, add a new TypeScript file named main.ts or you can add it as a new JavaScript file but the extension should be .ts.
main.ts
- import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
- import { AppModule } from './app.module';
- platformBrowserDynamic().bootstrapModule(AppModule);
The main.ts file has Angular module URL. You can change it if you have your module in other files. Here is my app.module code.
app.module.ts
- import { NgModule } from '@angular/core';
- import { APP_BASE_HREF } from '@angular/common';
- import { BrowserModule } from '@angular/platform-browser';
- import { ReactiveFormsModule } from '@angular/forms';
- import { AppComponent } from './app.component';
- import { Ng2Bs3ModalModule } from 'ng2-bs3-modal/ng2-bs3-modal';
- import { HttpModule } from '@angular/http';
- import { routing } from './app.routing';
- import { UserComponent } from './components/user.component';
- import { HomeComponent } from './components/home.component';
- import { CountryComponent } from './components/country.component';
- import { ArticleComponent } from './components/article.component';
- import { AdminComponent } from './components/admin.component';
- import { UserService} from './Service/user.service'
- import { CountryService} from './Service/country.service'
- import { ArticleService} from './Service/article.service'
- import { AdminService} from './Service/admin.service'
- @NgModule({
- imports: [BrowserModule, ReactiveFormsModule, HttpModule, routing, Ng2Bs3ModalModule],
- declarations: [AppComponent, UserComponent, HomeComponent, CountryComponent, ArticleComponent, AdminComponent],
- providers: [{ provide: APP_BASE_HREF, useValue: '/' }, UserService, CountryService, ArticleService, AdminService],
- bootstrap: [AppComponent]
- })
- export class AppModule { }
The app.module has references of all services, components, routing files.
Here is my routing:
App.routing.ts
- import { ModuleWithProviders } from '@angular/core';
- import { Routes, RouterModule } from '@angular/router';
- import { UserComponent } from './components/user.component';
- import { HomeComponent } from './components/home.component';
- import { CountryComponent } from './components/country.component';
- import { ArticleComponent } from './components/article.component';
- import { AdminComponent } from './components/admin.component';
- const appRoutes: Routes = [
- { path: '', redirectTo: 'home', pathMatch: 'full' },
- { path: 'home', component: HomeComponent },
- { path: 'user', component: UserComponent },
- { path: 'country', component: CountryComponent },
- { path: 'article', component: ArticleComponent },
- { path: 'admin', component: AdminComponent }
- ];
- export const routing: ModuleWithProviders =
- RouterModule.forRoot(appRoutes);
If routing you can change according to your requirement.
app.component.ts
There are two ways to define html and css in component, one way is you can make html in template tag and the other is you can make a new html page and css and define url in templateUrl.
- import {
- Component
- } from "@angular/core"
- @Component({
- selector: "user-app",
- template: `
- <div>
- <nav class='navbar navbar-inverse'>
- <div class='container-fluid'>
- <ul class='nav navbar-nav'>
- <li><a [routerLink]="['home']">Home</a></li>
- <li><a [routerLink]="['user']">Users Management</a></li>
- <li><a [routerLink]="['country']">Country</a></li>
- <li><a [routerLink]="['article']">Article</a></li>
- </ul>
- </div>
- </nav>
- <div class='container'>
- <router-outlet></router-outlet>
- </div>
- </div>
- `
- })
- export class AppComponent {}
Here you can see selector is your component name and template has display html, the other way you can do it is like this:
- import { Component } from "@angular/core"
- @Component({
- selector: "user-app",
- templateUrl: './app/app.component.html',
- styleUrls: ['./app/styles.css']
- })
- export class AppComponent {}
Here you need to give the html page's url and style url.
app.component.html
- <!DOCTYPE html>
- <html>
-
- <head>
- <title></title>
- <meta charset="utf-8" /> </head>
-
- <body>
- <div>
- <nav class='navbar navbar-inverse'>
- <div class='container-fluid'>
- <ul class='nav navbar-nav'>
- <li><a [routerLink]="['home']">Home</a></li>
- <li><a [routerLink]="['user']">Users Management</a></li>
- <li><a [routerLink]="['country']">Country</a></li>
- <li><a [routerLink]="['article']">Article</a></li>
- <li><a [routerLink]="['admin']">Admin</a></li>
- </ul>
- </div>
- </nav>
- <div class='container'>
- <router-outlet></router-outlet>
- </div>
- </div>
- </body>
-
- </html>
styles.css
- .html {
- overflow - y: scroll;
- overflow - x: hidden;
- }
- main {
- position: relative;
- padding - top: 60 px;
- }
- h1 {
- color: red;
- }
- h3 {
- color: green;
- }
Before adding other services and components and other related files, let’s work on index page. If you are using MVC applications then you need to add required files on _Layout.cshtml, if you are not using mcv then just add those files on index page.
_Layout.cshtml
- <!DOCTYPE html>
- <html>
-
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>@ViewBag.Title - My ASP.NET Application</title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr")
- <script src="/node_modules/core-js/client/shim.min.js"></script>
- <script src="/node_modules/zone.js/dist/zone.js"></script>
- <script src="/node_modules/systemjs/dist/system.src.js"></script>
- <script src="/systemjs.config.js"></script>
- <script>
- System.import('app').catch(function(err) {
- console.error(err);
- });
- </script>
- </head>
-
- <body>
- <div class="container body-content"> @RenderBody()
- <hr />
- <footer>
- <p>© @DateTime.Now.Year - My ASP.NET Application</p>
- </footer>
- </div> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body>
-
- </html>
Index.cshtml
- @{
- ViewBag.Title = "Index";
- }
- <body>
- <user-app>Loading…<user-app>
- </body>
Now let’s add other services, components and other related files. Let’s add a new folder name Model in app directory and add some typescript files and add related properties.
user.ts
- export interface IUser {
- AlbumId: number,
- GenreId: number,
- ArtistId: number,
- Title: string,
- Price: string,
- AlbumArtUrl: string,
- Artist: string
- }
country.ts
- export class Country {
- constructor(
- public id: number,
- public name: string) { }
- }
state.ts
- export class State {
- constructor(
- public id: number,
- public countryid: number,
- public name: string) { }
- }
article.ts
- export class Article{
- constructor(
- public Id: Number,
- public Title: string,
- public Summary: string
- ){}
- }
admin.ts
- export class Admin{
- constructor(
- public Id: Number,
- public Name: string
- ){}
- }
Now let’s add a new Shared folder and add two Typescript files:
global.ts
- export class Global {
- public static BASE_USER_ENDPOINT = 'api/albumapi/';
- }
enum.ts
- export enum DBOperation {
- create = 1,
- update = 2,
- delete =3
- }
Now add a new folder Services and add service Typescript files:
user.service.ts
- import {
- Injectable
- } from '@angular/core';
- import {
- Http,
- Response,
- Headers,
- RequestOptions
- } from '@angular/http';
- import {
- Observable
- } from 'rxjs/Observable';
- import 'rxjs/add/operator/map';
- import 'rxjs/add/operator/do';
- import 'rxjs/add/operator/catch';
- @Injectable()
- export class UserService {
- constructor(private _http: Http) {}
- get(url: string): Observable < any > {
- return this._http.get(url).map((response: Response) => < any > response.json())
-
- .catch(this.handleError);
- }
- post(url: string, model: any): Observable < any > {
- let body = JSON.stringify(model);
- let headers = new Headers({
- 'Content-Type': 'application/json'
- });
- let options = new RequestOptions({
- headers: headers
- });
- return this._http.post(url, body, options).map((response: Response) => < any > response.json()).catch(this.handleError);
- }
- put(url: string, id: number, model: any): Observable < any > {
- let body = JSON.stringify(model);
- let headers = new Headers({
- 'Content-Type': 'application/json'
- });
- let options = new RequestOptions({
- headers: headers
- });
- return this._http.put(url + id, body, options).map((response: Response) => < any > response.json()).catch(this.handleError);
- }
- delete(url: string, id: number): Observable < any > {
- let headers = new Headers({
- 'Content-Type': 'application/json'
- });
- let options = new RequestOptions({
- headers: headers
- });
- return this._http.delete(url + id, options).map((response: Response) => < any > response.json()).catch(this.handleError);
- }
- private handleError(error: Response) {
- console.error(error);
- return Observable.throw(error.json().error || 'Server error');
- }
- }
country.service.ts
- import { Injectable } from '@angular/core';
- import { Country } from '../model/country';
- import { State } from '../model/state';
- @Injectable()
- export class CountryService {
- getCountries() {
- return [
- new Country(1, 'United States'),
- new Country(2, 'India'),
- new Country(3, 'Australia'),
- new Country(4, 'New Zealand'),
- new Country(5, 'South Africa'),
- new Country(6, 'United Kingdom')
- ];
- }
- getStates() {
- return [
- new State(1, 1, 'Alabama'),
- new State(2, 1, 'Alaska'),
- new State(3, 1, 'Arizona'),
- new State(5, 1, 'Arkansas'),
- new State(6, 1, 'California'),
- new State(7, 1, 'Colorado'),
- new State(8, 1, 'Connecticut'),
- new State(9, 1, 'Delaware'),
- new State(10, 1, 'Florida'),
- new State(11, 1, 'Georgia'),
- new State(12, 1, 'Hawaii'),
- new State(13, 1, 'Idaho'),
- new State(14, 1, 'Illinois'),
- new State(15, 1, 'Indiana'),
- new State(16, 2, 'New Delhi'),
- new State(17, 2, 'Maharashtra'),
- new State(18, 2, 'Goa'),
- new State(19, 2, 'Punjab'),
- new State(20, 2, 'Haryana'),
- new State(21, 2, 'Uttar Pradesh'),
- new State(22, 2, 'Rajasthan'),
- new State(23, 2, 'Andhra Pradesh'),
- new State(24, 2, 'Jharkhand'),
- new State(25, 2, 'Madhya Pradesh'),
- new State(26, 3, 'New South Wales'),
- new State(27, 3, 'Tasmania'),
- new State(28, 3, 'Qweensland'),
- new State(29, 3, 'Western Australia'),
- new State(30, 3, 'Victoria'),
- new State(31, 4, 'Auckland'),
- new State(32, 4, 'Wellington'),
- new State(33, 4, 'Christchurch'),
- new State(34, 4, 'Hamilton'),
- new State(35, 4, 'Napier'),
- new State(31, 5, 'Eastern Cape'),
- new State(32, 5, 'Limpopo'),
- new State(33, 5, 'Mpumalanga'),
- new State(34, 5, 'North West'),
- new State(35, 5, 'Northern Cape'),
- new State(31, 6, 'Herefordshire'),
- new State(32, 6, 'Durham'),
- new State(33, 6, 'Manchester'),
- new State(34, 6, 'South Yorkshire'),
- new State(35, 6, 'Birmingham')
- ];
- }
- }
article.service.ts
- import { Injectable } from '@angular/core';
- import { Article } from '../model/article';
- @Injectable()
- export class ArticleService {
- ARTICLES: Article[] = [
- { Id: 1, Title: 'Angular 2 - Getting Started', Summary: 'In this article, you will learn how to start working with Angular 2.' },
- { Id: 2, Title: 'How to detect image Faces and make Blur using Cognitive Face API with .NET Core', Summary: 'In this article, you will learn how to detect total faces and image and make them Blur using Cognitive Face API with .NET Core.' },
- { Id: 3, Title: 'Getting Started With Microsoft Project 2016', Summary: 'In this article, you will learn how to getting started with Microsoft Project 2016 from scratch.' },
- { Id: 4, Title: 'Get Image Attributes using Cognitive Services face API in WPF', Summary: 'In this article you will learn how to get the image attributes like Age, Gender using Cognitive Services face API in WPF.' },
- { Id: 5, Title: 'Cognitive Services face API in WPF', Summary: 'In this article, I will explain how to use Cognitive Services face API in WPF.' }
- ];
- }
admin.service.ts
- import { Injectable } from '@angular/core';
- import { Admin } from '../model/admin';
- @Injectable()
- export class AdminService {
- ADMIN: Admin[] = [
- { Id: 1, Name: 'Raj Kumar' },
- { Id: 2, Name: 'Preeti' }
- ];
- }
Now let’s add new folder components and add some components and html and stylesheets:
user.component.ts
- import {
- Component,
- OnInit,
- ViewChild
- } from '@angular/core';
- import {
- UserService
- } from '../Service/user.service';
- import {
- FormBuilder,
- FormGroup,
- Validators
- } from '@angular/forms';
- import {
- ModalComponent
- } from 'ng2-bs3-modal/ng2-bs3-modal';
- import {
- IUser
- } from '../Model/user';
- import {
- DBOperation
- } from '../Shared/enum';
- import {
- Observable
- } from 'rxjs/Rx';
- import {
- Global
- } from '../Shared/global';
- @Component({
- templateUrl: 'app/Components/user.component.html'
- })
- export class UserComponent implements OnInit {
- @ViewChild('modal') modal: ModalComponent;
- users: IUser[];
- user: IUser;
- msg: string;
- indLoading: boolean = false;
- userFrm: FormGroup;
- dbops: DBOperation;
- modalTitle: string;
- modalBtnTitle: string;
- constructor(private fb: FormBuilder, private _userService: UserService) {}
- ngOnInit(): void {
- this.userFrm = this.fb.group({
- AlbumId: [''],
- GenreId: [''],
- ArtistId: [''],
- Title: ['', Validators.required],
- Price: [''],
- AlbumArtUrl: ['', Validators.required],
- Artist: ['']
- });
- this.LoadUsers();
- }
- LoadUsers(): void {
- this.indLoading = true;
- this._userService.get(Global.BASE_USER_ENDPOINT).subscribe(users => {
- this.users = users;
- this.indLoading = false;
- }, error => this.msg = < any > error);
- }
- addUser() {
- this.dbops = DBOperation.create;
- this.SetControlsState(true);
- this.modalTitle = "Add New User";
- this.modalBtnTitle = "Add";
- this.userFrm.reset();
- this.modal.open();
- }
- editUser(AlbumId: number) {
- this.dbops = DBOperation.update;
- this.SetControlsState(true);
- this.modalTitle = "Edit User";
- this.modalBtnTitle = "Update";
- this.user = this.users.filter(x => x.AlbumId == AlbumId)[0];
- this.userFrm.setValue(this.user);
- this.modal.open();
- }
- deleteUser(AlbumId: number) {
- this.dbops = DBOperation.delete;
- this.SetControlsState(false);
- this.modalTitle = "Confirm to Delete?";
- this.modalBtnTitle = "Delete";
- this.user = this.users.filter(x => x.AlbumId == AlbumId)[0];
- this.userFrm.setValue(this.user);
- this.modal.open();
- }
- onSubmit(formData: any) {
- this.msg = "";
- switch (this.dbops) {
- case DBOperation.create:
- this._userService.post(Global.BASE_USER_ENDPOINT, formData._value).subscribe(data => {
- if (data == 1)
- {
- this.msg = "Data successfully added.";
- this.LoadUsers();
- } else {
- this.msg = "There is some issue in saving records, please contact to system administrator!"
- }
- this.modal.dismiss();
- }, error => {
- this.msg = error;
- });
- break;
- case DBOperation.update:
- this._userService.put(Global.BASE_USER_ENDPOINT, formData._value.AlbumId, formData._value).subscribe(data => {
- if (data == 1)
- {
- this.msg = "Data successfully updated.";
- this.LoadUsers();
- } else {
- this.msg = "There is some issue in saving records, please contact to system administrator!"
- }
- this.modal.dismiss();
- }, error => {
- this.msg = error;
- });
- break;
- case DBOperation.delete:
- this._userService.delete(Global.BASE_USER_ENDPOINT, formData._value.AlbumId).subscribe(data => {
- if (data == 1)
- {
- this.msg = "Data successfully deleted.";
- this.LoadUsers();
- } else {
- this.msg = "There is some issue in saving records, please contact to system administrator!"
- }
- this.modal.dismiss();
- }, error => {
- this.msg = error;
- });
- break;
- }
- }
- SetControlsState(isEnable: boolean) {
- isEnable ? this.userFrm.enable() : this.userFrm.disable();
- }
- }
user.component.html
- <div class='panel panel-primary'>
- <div class='panel-heading'> User Management </div>
- <div class='panel-body'>
- <div class='table-responsive'>
- <div style="padding-bottom:10px"><button class="btn btn-primary" (click)="addUser()">Add</button></div>
- <div class="alert alert-info" role="alert" *ngIf="indLoading"><img src="../../images/loading.gif" width="32" height="32" /> Loading...</div>
- <div *ngIf='users && users.length==0' class="alert alert-info" role="alert">No record found!</div>
- <table class='table table-striped' *ngIf='users && users.length'>
- <thead>
- <tr>
- <th>Title</th>
- <th>Price</th>
- <th>URL</th>
- <th></th>
- </tr>
- </thead>
- <tbody>
- <tr *ngFor="let user of users">
- <td>{{user.Title}}</td>
- <td>{{user.Price}}</td>
- <td>{{user.AlbumArtUrl}}</td>
- <td> <button title="Edit" class="btn btn-primary" (click)="editUser(user.AlbumId)">Edit</button> <button title="Delete" class="btn btn-danger" (click)="deleteUser(user.AlbumId)">Delete</button> </td>
- </tr>
- </tbody>
- </table>
- <div> </div>
- </div>
- <div *ngIf="msg" role="alert" class="alert alert-info alert-dismissible"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button> <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span> <span class="sr-only">Error:</span> {{msg}} </div>
- </div>
- </div>
- <modal #modal>
- <form novalidate (ngSubmit)="onSubmit(userFrm)" [formGroup]="userFrm">
- <modal-header [show-close]="true">
- <h4 class="modal-title">{{modalTitle}}</h4>
- </modal-header>
- <modal-body>
- <div class="form-group">
- <div> <span>Title*</span> <input type="text" class="form-control" placeholder="Title" formControlName="Title"> </div>
- <div> <span>Price</span> <input type="text" class="form-control" placeholder="Price" formControlName="Price"> </div>
- <div> <span>AlbumArtUrl*</span> <input type="text" class="form-control" placeholder="URL" formControlName="AlbumArtUrl"> </div>
- </div>
- </modal-body>
- <modal-footer>
- <div> <a class="btn btn-default" (click)="modal.dismiss()">Cancel</a> <button type="submit" [disabled]="userFrm.invalid" class="btn btn-primary">{{modalBtnTitle}}</button> </div>
- </modal-footer>
- </form>
- </modal>
home.component.ts
- import { Component } from "@angular/core";
- @Component({
- template: `<h1>This is home page!</h1>`
- })
- export class HomeComponent{
- }
country.component.ts
- import {
- Component
- } from '@angular/core';
- import {
- CountryService
- } from '../Service/country.service';
- import {
- Country
- } from '../model/country';
- import {
- State
- } from '../model/state';
- @Component({
- selector: 'country-component',
- templateUrl: 'app/components/countrycomponent.html',
- providers: [CountryService]
- })
- export class CountryComponent {
- selectedCountry: Country = new Country(0, 'India');
- countries: Country[];
- states: State[];
- constructor(private _countryService: CountryService) {
- this.countries = this._countryService.getCountries();
- }
- onSelect(countryid) {
- this.states = this._countryService.getStates().filter((item) => item.countryid == countryid);
- }
- }
countrycomponent.html
- <div class='panel panel-primary'>
- <div class='panel-heading'> Country Management </div>
- <div class='panel-body'>
- <div class='table-responsive'> <label>Country:</label> <select (change)="onSelect($event.target.value)">
- <option value="0">--Select Country--</option>
- <option *ngFor="let country of countries" value={{country.id}}>{{country.name}}</option>
- </select> <br /><br />
- <div> <label>State:</label> <select>
- <option *ngIf='selectedCountry.id == 0' value="0">--Select State--</option>
- <option *ngFor="let state of states " value={{state.id}}>{{state.name}}</option>
- </select> </div>
- </div>
- </div>
- </div>
article.component.ts
- import { Component } from '@angular/core';
- import { ArticleService } from '../Service/article.service';
- import { Article } from '../Model/Article';
- @Component({
- selector: 'article-component',
- templateUrl: 'app/components/articlecomponent.html',
- providers: [ArticleService]
- })
- export class ArticleComponent {
- articles: Article[];
- constructor(private _articleService: ArticleService) {
- }
- }
articlecomponent.html
- <div class='panel panel-primary'>
- <div class='panel-heading'>
- Article Management
- </div>
- <div class='panel-body'>
- <div class='table-responsive'>
- <h1>Article list</h1>
- </div>
- </div>
- </div>
admin.component.ts
- import { Component } from '@angular/core';
- import { AdminService } from '../Service/admin.service';
- import { Admin } from '../Model/admin';
- @Component({
- selector: 'admin-component',
- templateUrl: 'app/components/admincomponent.html',
- providers: [AdminService]
- })
- export class AdminComponent {
- admins: Admin[];
- constructor(private _adminService: AdminService) {
- }
- }
admincomponent.html
- <div class='panel panel-primary'>
- <div class='panel-heading'>
- Admin Management
- </div>
- <div class='panel-body'>
- <div class='table-responsive'>
- <h1>Admin list</h1>
- </div>
- </div>
- </div>
I think we are good now. Time to run the application to see the result screen.
If your home page loaded without error that means everything is good. As you can see on the header we have four navigation menus, if you click on User Management:
Data is loading from database and routing is also working well. Most people ask me this question about routing in Angular 2, so I would recommend this article for routing as well.
Now click on Edit button.
Change something and click on Update button. If you want to delete any row then click on Delete button then this model screen should open.
If you want to add new data, then simply click on Add button.
Now let’s check other navigation clicks to check weather and see if everything is working or not.
You can select any country, then all related states will bind in drop down. If you click on Article then empty window will load because I did not do any functionality for this.
Conclusion
In this article, we learned the basics for Angular 2 like loading data from Web API, Routing, and use of services and components. If you have questions or comments, please drop me a line in the comments section.