It's Angular Demo Time

In this tutorial I am not going to discuss more about Angular concepts, I already discussed that in the below links. To understand this demo better, first of all, please go through the below links before proceeding further.

I will demonstrate a few features of Angular 2 and above versions with a small demo application. Here is the below content which I am going to cover as part of this demo application:

  1. Create an angular application by following quick start
  2. Create a component ‘nav.component’ with application title and navigation links.

    1. Navigation Links

      1. Users
      2. Todos
      3. Albums

    2. The navigation menu should be available on every page and corresponding menu items should be highlighted when you visit a route.

  3. Create a component named ‘user.list.component’ which shows information about users.
    1. On clicking a ‘user’ item it should redirect to a new route (user/userid) which shows all the information about the user

      • User posts
      • User albums
      • User to-do’s

        Each of the above posts, albums and todos are individual components which retrieve required information based on userids from respective services.
        1. Demonstrate *ngFor directive with li’s/tr’s
        2. Demonstrate ngClass, ngModel
        3. Demonstrate interpolation and two-way binding
        4. Demonstrate *ngIf. Show ‘No Data’ message there is data is available.
  1. Create a component named ‘post.list.component’ which shows user posts when a userid parameter is sent.

  2. Create a component named ‘album.list.component’ which shows a user album when a userid parameter is sent. If a parameter is not available show all albums.

  3. Create a component named ‘todo.list.component’ which shows the user to do when a parameter is sent if a parameter is not available to show all albums

  4. All services should follow these rules

    1. Demonstrate rxjs observables
    2. Error handling
    3. Dependency Injection (Inject the service where ever required)

  5. Create a component named ‘search.component’ which helps a user to perform search operations

    1. It should have input[type=text], ‘search’ button and ‘clear’ button.
    2. On clicking ‘search’, component should emit an event with search criteria to parent component
    3. Use search component in the user list and album list components.
    4. Search component label should change to ‘user’ or ‘album’ based on the type of parent component.

  6. Create a directive ‘highlight.directive.ts’ which should highlight (the color of the text should change to ‘red’) all the users who have ‘LLC’ in the company name.

  7. Demonstrate form validation with angular by creating a new user registration page.

    1. A new button on ‘user.list.component’ should navigate to a new route (user/new)
    2. Create a user, address classes and bind them to create a registration page.
    3. A form should have following fields. Submit event should take the user object and log into the console.

      • FirstName*
      • LastName*
      • MiddleName
      • Email*
      • Street*
      • Country*
      • City*
        • required field.
  1. Integrate a third-party module into your application and demonstrate it (the third party can be anything)

Ex: ng2-bootstrap, PrimeNG for Angular2, Material designs for Angular2 (I like this)

  1. The template layouts (HTML design) is up to your creativity.

  2. Organize your code in the following folder structure

    Angular

Note

  • Make sure your import statements are written well. All packages are case-sensitive.
  • Make sure all your CSS/less/sass files are component specific.
  • In case of wrong imports, compilation may work fine sometimes but module loading will fail.
  • Verify that you are running node v4.x.x or higher and npm 3.x.x or higher

Please do have a clear understanding of the below files,

  • json
  • json
  • config.js

Source code for point number #2

nav.component.html

  1. <!-- Static navbar -->  
  2. <nav class="navbar navbar-default">  
  3.   <div class="container">  
  4.     <div class="navbar-header">  
  5.       <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">  
  6.         <span class="sr-only">Toggle navigation</span>  
  7.         <span class="icon-bar"></span>  
  8.         <span class="icon-bar"></span>  
  9.         <span class="icon-bar"></span>  
  10.       </button>  
  11.       <a class="navbar-brand" href="#">Anguar2 Sample</a>  
  12.     </div>  
  13.     <div id="navbar" class="navbar-collapse collapse">  
  14.       <ul class="nav navbar-nav">  
  15.         <li [routerLinkActive]="['active']" class="active"><a routerLink="/users" href="#">Users</a></li>  
  16.         <li [routerLinkActive]="['active']"><a routerLink="/todos" href="# ">Todos</a></li>  
  17.         <li [routerLinkActive]="['active']"><a routerLink="/albums" href="# ">Albums</a></li>  
  18.       </ul>  
  19.     </div>  
  20.     <!--/.nav-collapse -->  
  21.   </div>  
  22.   <!--/.container-fluid -->  
  23. </nav>  

nav.component.ts

  1. import { Component, OnInit } from '@angular/core';  
  2. // import { ActivatedRoute } from '@angular/router';  
  3.   
  4. @Component({  
  5.   moduleId: module.id,  
  6.   selector: 'navmenu',  
  7.   templateUrl: 'nav.component.html'  
  8. })  
  9. export class NavComponent implements OnInit {  
  10.   constructor() { }  
  11.   ngOnInit() {  }  
  12. }  

app.module.ts

  1. import { NgModule } from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3. import { FormsModule } from '@angular/forms';  
  4. import { HttpModule } from '@angular/http';  
  5. import { RouterModule } from '@angular/router';  
  6. import { AppComponent } from './app.component';  
  7. import { NavComponent } from './components/nav/nav.component';  
  8.   
  9. @NgModule({  
  10.   imports: [NgbModule.forRoot(), BrowserModule, FormsModule, HttpModule, RouterModule.forRoot(APP_ROUTES)],  
  11.   declarations: [NavComponent, AppComponent],  
  12.   bootstrap: [AppComponent],  
  13.   providers: [UserService]  
  14. })  
  15. export class AppModule { } 

app.component.ts

  1. import { Component } from '@angular/core';  
  2. @Component({  
  3.   selector: 'my-app',  
  4.   template: `<navmenu></navmenu>  
  5.     <router-outlet></router-outlet>  
  6.     `  
  7. })  
  8. export class AppComponent {  
  9.   ChildEvent(event: any) {  
  10.     console.log(event);  
  11.   }  
  12. }  

Output

Angular

Source code for point number #3

user.list.component.css

  1. ul {  
  2.   list-style-type: none;  
  3.   margin: 0;  
  4.   padding: 0;  
  5. }  
  6.   
  7. ul.cards>li {  
  8.   padding: 5px;  
  9.   cursor: pointer;  
  10.   margin: 10px;  
  11.   width: 200px;  
  12.   height: 300px;  
  13.   vertical-align: top;  
  14.   border: 1px solid #ccc;  
  15.   box-shadow: 10px 10px 5px #CCC;  
  16.   display: inline-block;  
  17. }  
  18.   
  19. ul.cards>li:hover {  
  20.   border: 1px solid deepskyblue;  
  21.   box-shadow: 15px 15px 5px #CCC;  
  22. }  
  23.   
  24. section.users {  
  25.   padding: 5px;  

user.list.component.html

  1. <div class="container">  
  2.   <div class="row">  
  3.     <div class="col-md-7">  
  4.       <search-component (goClicked)="searchTriggered($event)" (clearClicked)="clearTriggered($event)"></search-component>  
  5.     </div>  
  6.     <div class="col-md-3">  
  7.       <div class="btn-group pull-right">  
  8.         <button type="button" class="btn" [ngClass]="!isDetailsView ? 'btn btn-success' : 'btn'" (click)="toggle(false)">List</button>  
  9.         <button type="button" class="btn" [ngClass]="isDetailsView ? 'btn btn-success' : 'btn'" (click)="toggle(true)">Detail</button>  
  10.       </div>  
  11.     </div>  
  12.     <div class="col-md-2">  
  13.       <a routerLink="/users/new" href="#" class="btn btn-success">New</a>  
  14.     </div>  
  15.   </div>  
  16.   <div class="row">  
  17.     <div class="col-md-12">  
  18.       <section class="users">  
  19.         <table class="table table-bordered table-hover" *ngIf="!isDetailsView">  
  20.           <thead>  
  21.           <tr>  
  22.             <td><strong>Name</strong></td>  
  23.             <td><strong>Email</strong></td>  
  24.             <td><strong>Phone</strong></td>  
  25.             <td><strong>Website</strong></td>  
  26.           </tr>  
  27.           </thead>  
  28.           <tbody>  
  29.           <tr *ngFor="let usr of filteredData">  
  30.             <td>{{usr.name}}</td>  
  31.             <td>{{usr.email}}</td>  
  32.             <td>{{usr.phone | uppercase}}</td>  
  33.             <td>  
  34.               <a target="_blank" href="http://{{usr.website}}">{{usr.website}}</a>  
  35.             </td>  
  36.           </tr>  
  37.           </tbody>  
  38.           <tbody *ngIf="filteredData.length === 0">  
  39.           <tr>  
  40.             <td colspan="4">  
  41.               <h1>No Data!</h1>  
  42.             </td>  
  43.           </tr>  
  44.           </tbody>  
  45.         </table>  
  46.       </section>  
  47.     </div>  
  48.   </div>  
  49.   <div class="row">  
  50.     <div class="col-md-12">  
  51.       <section class="users" *ngIf="isDetailsView">  
  52.         <ul class="cards">  
  53.           <li *ngFor="let usr of filteredData" (click)="showUser(usr)" hover highlight>  
  54.             <p><strong>{{usr.name}}</strong></p>  
  55.             <em><a target="_blank" href="http://{{usr.website}}">{{usr.website}}</a></em>  
  56.             <p>Street: {{usr.address?.street}}</p>  
  57.             <p>suite: {{usr.address?.suite}}</p>  
  58.             <p>city: {{usr.address?.city}}</p>  
  59.             <p>zipcode: {{usr.address?.zipcode}}</p>  
  60.             <em><a target="_blank" href="http://{{usr.website}}">{{usr.website}}</a></em>  
  61.           </li>  
  62.         </ul>  
  63.       </section>  
  64.     </div>  
  65.   </div>  
  66. </div> 

user.list.component.ts

  1. import {  
  2.   Component, Input,  
  3.   OnInit  
  4. } from '@angular/core';  
  5. import { UserService } from '../../services/user.service';  
  6. // import { SearchComponent } from '../filter/search.component';  
  7. import { Router } from '@angular/router';  
  8.   
  9. @Component({  
  10.   selector: 'user-list',  
  11.   templateUrl: 'app/components/user/user.list.component.html',  
  12.   styleUrls: ['app/components/user/user.list.component.css']  
  13. })  
  14. export class UserListComponent implements OnInit {  
  15.   @Input('userdata') users: any[] = [];  
  16.   /*    @Output() goClicked: EventEmitter<any> = new EventEmitter<any>();*/  
  17.   searchFilter: string = '';  
  18.   isDetailsView: boolean = true;  
  19.   filteredData: any[];  
  20.   
  21.   constructor(private _userService: UserService, private _router: Router) {  
  22.     console.log('I am constructor!');  
  23.   }  
  24.   
  25.   toggle(isDetailsView: any) {  
  26.     console.log(isDetailsView);  
  27.     this.isDetailsView = isDetailsView;  
  28.   }  
  29.   
  30.   ngOnInit() {  
  31.     this._userService.getUsers().subscribe((users) => {  
  32.       this.filteredData = this.users = users;  
  33.     }, error => {  
  34.       console.error('Error in UserList', error);  
  35.     });  
  36.   }  
  37.   
  38.   
  39.   /*searchFilterChange() { 
  40.       console.log("Changed.."); 
  41.   } 
  42.  
  43.   searchUsers() { 
  44.       this.goClicked.emit({ 
  45.           wdfsd: "sdfsdf", 
  46.           searchFilter: this.searchFilter 
  47.       }); 
  48.       this.filteredData = this.users.filter((item) => { 
  49.           return item.name.toLowerCase().indexOf(this.searchFilter.toLowerCase()) > -1; 
  50.       }); 
  51.   }*/  
  52.   
  53.   clear() {  
  54.     this.searchFilter = '';  
  55.     this.filteredData = this.users;  
  56.   }  
  57.   
  58.   showUser(user: any) {  
  59.     this._router.navigate(['/user', user.id]);  
  60.   }  
  61.   
  62.   clearTriggered(){  
  63.   
  64.     this.filteredData = this.users;  
  65.   }  
  66.   
  67.   searchTriggered(data: any) {  
  68.     console.log('user list search button click event');  
  69.     this.filteredData = this.users.filter((item) => {  
  70.       return item.name.toLowerCase().indexOf(data.searchText.toLowerCase()) > -1;  
  71.     });  
  72.   }  

user.component.ts

  1. import { Component, OnInit } from '@angular/core';  
  2. import { ActivatedRoute } from '@angular/router';  
  3. import { UserService } from '../../services/user.service';  
  4.   
  5. @Component({  
  6.   moduleId: module.id,  
  7.   selector: 'user',  
  8.   providers: [UserService],  
  9.   template: `  
  10.     <a routerLink="/users">Back to Users</a>  
  11. <hr>  
  12.     <ul class="cards">  
  13.         <li>  
  14.             <p><strong>{{usr.name}}</strong></p>  
  15.             <p>Street: {{usr.address?.street}}</p>  
  16.             <p>suite: {{usr.address?.suite}}</p>  
  17.             <p>city: {{usr.address?.city}}</p>  
  18.             <p>zipcode: {{usr.address?.zipcode}}</p>  
  19.             <em><a target="_blank" href="http://{{usr.website}}">{{usr.website}}</a></em>  
  20.         </li>  
  21.     </ul>  
  22.     `  
  23. })  
  24. export class UserComponent implements OnInit {  
  25.   usr: any = {};  
  26.   constructor(private aroute: ActivatedRoute,  
  27.               private _userService: UserService) { }  
  28.   
  29.   ngOnInit() {  
  30.     this.aroute.params.subscribe((params) => {  
  31.       let userId = params['id'];  
  32.       this._userService.getUser(userId).subscribe((user) => {  
  33.         this.usr = user;  
  34.       });  
  35.     });  
  36.   }  

app.module.ts

  1. import { NgModule } from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3. import { FormsModule } from '@angular/forms';  
  4. import { HttpModule } from '@angular/http';  
  5. import { RouterModule } from '@angular/router';  
  6.   
  7. import { AppComponent } from './app.component';  
  8. import { UserListComponent} from './components/user/user.list.component';  
  9. import { NavComponent } from './components/nav/nav.component';  
  10. import { SearchComponent } from './components/filter/search.component';  
  11. import { APP_ROUTES } from './app.routes';  
  12. import { UserComponent } from './components/user/user.component';  
  13. import { UserService } from './services/user.service';  
  14.   
  15.   
  16. @NgModule({  
  17.   imports: [BrowserModule, FormsModule, HttpModule, RouterModule.forRoot(APP_ROUTES)],  
  18.   declarations: [SearchComponent, NavComponent, AppComponent, UserListComponent, UserComponent  
  19. ],  
  20.   bootstrap: [AppComponent],  
  21.   providers: [UserService]  
  22. })  
  23. export class AppModule { }  

Output

Angular

When we click on Users then by default it is the Detail, output as below,

Angular

If we click on List view then below is the output,

Angular

Source code for point number #4

post.list.component.ts

  1. import { Component } from '@angular/core';  
  2. import { UserService } from '../../services/user.service';  
  3.   
  4. @Component({  
  5.   selector: 'post-list',  
  6.   template: `Yet to..`  
  7. })  
  8. export class PostListComponent {  
  9.   constructor(private _userService: UserService) {}  
  10.   
  11.   ngOnInit() {  
  12.     this._userService.getUsers()  
  13.       .subscribe((data) => {  
  14.         console.log(data);  
  15.       });  
  16.   }  

app.module.ts

  1. import { NgModule } from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3. import { FormsModule } from '@angular/forms';  
  4. import { HttpModule } from '@angular/http';  
  5. import { RouterModule } from '@angular/router';  
  6.   
  7. import { AppComponent } from './app.component';  
  8. import { UserListComponent} from './components/user/user.list.component';  
  9. import { NewUserComponent } from './components/user/new.user.component'  
  10. import { TodoComponent } from './components/todo/todo.component';  
  11. import { NavComponent } from './components/nav/nav.component';  
  12. import { PostListComponent } from './components/posts/post.list.component';  
  13. import { UserService } from './services/user.service';  
  14. import { SearchComponent } from './components/filter/search.component';  
  15. import { APP_ROUTES } from './app.routes';  
  16. import { NgbdModalBasic } from './components/user/modal-basic';  
  17.   
  18. @NgModule({  
  19.   imports: [BrowserModule, FormsModule, HttpModule, RouterModule.forRoot(APP_ROUTES)],  
  20.   declarations: [SearchComponent, NavComponent, AppComponent, UserListComponent, PostListComponent],  
  21.   bootstrap: [AppComponent],  
  22.   providers: [UserService]  
  23. })  
  24. export class AppModule { } 

Source code for point number #5

album.list.component.html

  1. <div class="container">  
  2.   <div class="row">  
  3.     <search-component (goClicked)="searchTriggered($event)" (clearClicked)="clearTriggered($event)"></search-component>  
  4.   </div>  
  5.   <div class="row">  
  6.     <div *ngFor="let album of albumlist">  
  7.       <div class="alert">  
  8.         <strong>{{album.userId}}</strong> {{album.title}}  
  9.       </div>  
  10.     </div>  
  11.   </div>  
  12. </div>  

album.list.component.ts

  1. import { Component, Input } from '@angular/core';  
  2. import { AlbumService } from '../../services/album.service';  
  3. // import { SearchComponent } from '../filter/search.component';  
  4. import { ActivatedRoute } from '@angular/router';  
  5.   
  6. @Component({  
  7.   moduleId: module.id,  
  8.   selector: 'album-list',  
  9.   templateUrl: 'album.list.component.html',  
  10.   providers: [AlbumService]  
  11. })  
  12. export class AlbumListComponent {  
  13.   @Input('albumlist') _albumlist: any[] = [];  
  14.   albumlist: any[];  
  15.   constructor(private _albumService: AlbumService,  
  16.               private aroute: ActivatedRoute) {  
  17.   
  18.   }  
  19.   
  20.   ngOnInit() {  
  21.     this.aroute.params.subscribe((data) => {  
  22.       let userid = data['id'];  
  23.       console.log(userid);  
  24.       if (userid) {  
  25.         this._albumService.getAlbumByUserId(userid).subscribe((data) => {  
  26.           this.albumlist = data;  
  27.           console.log(data);  
  28.         });  
  29.       } else {  
  30.         this._albumService.getAlbums().subscribe((data) => {  
  31.           this.albumlist = this._albumlist = data;  
  32.         });  
  33.       }  
  34.   
  35.     });  
  36.   }  
  37.   clearTriggered() {  
  38.     this.albumlist = this._albumlist;  
  39.   }  
  40.   searchTriggered(data: any) {  
  41.     console.log('album list search button click event');  
  42.     this.albumlist = this.albumlist.filter((item) => {  
  43.       return item.title.toLowerCase().indexOf(data.searchText.toLowerCase()) > -1;  
  44.     });  
  45.   }  

album.service.ts

  1. import { Injectable } from '@angular/core';  
  2. import { Http } from '@angular/http';  
  3. import 'rxjs/add/operator/map';  
  4.   
  5. @Injectable()  
  6. export class AlbumService {  
  7.   url: string = 'https://jsonplaceholder.typicode.com/';  
  8.   constructor(private _http: Http) { }  
  9.   
  10.   getAlbums() {  
  11.     let albumUrl = this.url + 'albums';  
  12.     return this._http.get(albumUrl)  
  13.       .map((res) => { return res.json(); });  
  14.   }  
  15.   
  16.   getAlbumByUserId(id: number) {  
  17.     let albumUrl = `${this.url}albums`;  
  18.     return this._http.get(albumUrl + '?userId=' + id)  
  19.       .map((res) => { return res.json(); });  
  20.   }  

app.module.ts

  1. import { NgModule } from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3. import { FormsModule } from '@angular/forms';  
  4. import { HttpModule } from '@angular/http';  
  5. import { RouterModule } from '@angular/router';  
  6. import { AppComponent } from './app.component';  
  7. import { UserListComponent} from './components/user/user.list.component';  
  8. import { TodoComponent } from './components/todo/todo.component';  
  9. import { NavComponent } from './components/nav/nav.component';  
  10. import { PostListComponent } from './components/posts/post.list.component';  
  11. import { UserService } from './services/user.service';  
  12. import { AlbumListComponent } from './components/albums/album.list.component';  
  13. import { SearchComponent } from './components/filter/search.component';  
  14. import { APP_ROUTES } from './app.routes';  
  15. import { NgbdModalBasic } from './components/user/modal-basic';  
  16.   
  17. @NgModule({  
  18.   imports: [BrowserModule, FormsModule, HttpModule, RouterModule.forRoot(APP_ROUTES)],  
  19.   declarations: [SearchComponent, AlbumListComponent, TodoComponent, NavComponent, AppComponent, UserListComponent, PostListComponent],  
  20.   bootstrap: [AppComponent],  
  21.   providers: [UserService]  
  22. })  
  23. export class AppModule { }  

Output

Angular

Source code for point number #6

todo.component.html

  1. <div class="container">  
  2.   <div class="row">  
  3.     <div *ngFor="let todo of todos">  
  4.       <div class="alert">  
  5.         <strong>{{todo.userId}}</strong> {{todo.title}}  
  6.       </div>  
  7.     </div>  
  8.   </div>  
  9. </div> 

todo.component.ts

  1. import { Component, OnInit } from '@angular/core';  
  2. import { TodoService } from '../../services/todo.service';  
  3. import { ActivatedRoute } from '@angular/router';  
  4.   
  5. @Component({  
  6.   moduleId: module.id,  
  7.   selector: 'todo',  
  8.   templateUrl: 'todo.component.html',  
  9.   providers: [TodoService]  
  10. })  
  11. export class TodoComponent implements OnInit {  
  12.   todos: any[];  
  13.   constructor(private _todoService: TodoService,  
  14.               private aroute: ActivatedRoute) {  
  15.   
  16.   }  
  17.   
  18.   ngOnInit() {  
  19.     this.aroute.params.subscribe((data) => {  
  20.       let userid = data['id'];  
  21.       console.log(userid);  
  22.       if (userid) {  
  23.         this._todoService.getTodosByUserId(userid).subscribe((data) => {  
  24.           this.todos = data;  
  25.           console.log(data);  
  26.         });  
  27.       } else {  
  28.         this._todoService.getTodos().subscribe((data) => {  
  29.           this.todos = data;  
  30.         });  
  31.       }  
  32.   
  33.     });  
  34.   
  35.   }  

todo.service.ts

  1. import { Injectable } from '@angular/core';  
  2. import { Http } from '@angular/http';  
  3. import 'rxjs/add/operator/map';  
  4.   
  5. @Injectable()  
  6. export class TodoService {  
  7.   url: string = 'https://jsonplaceholder.typicode.com/';  
  8.   constructor(private _http: Http) { }  
  9.   
  10.   getTodos() {  
  11.     let todoUrl = this.url + 'todos'//`${this.url}todos`  
  12.     return this._http.get(todoUrl)  
  13.       .map((res) => { return res.json(); });  
  14.   }  
  15.   
  16.   getTodosByUserId(id: number) {  
  17.     let todoUrl = `${this.url}todos`;  
  18.     return this._http.get(todoUrl + '?userId=' + id)  
  19.       .map((res) => { return res.json(); });  
  20.   }  

app.module.ts

  1. import { NgModule } from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3. import { FormsModule } from '@angular/forms';  
  4. import { HttpModule } from '@angular/http';  
  5. import { RouterModule } from '@angular/router';  
  6. import { AppComponent } from './app.component';  
  7. import { UserListComponent} from './components/user/user.list.component';  
  8. import { NewUserComponent } from './components/user/new.user.component'  
  9. import { TodoComponent } from './components/todo/todo.component';  
  10. import { NavComponent } from './components/nav/nav.component';  
  11. import { PostListComponent } from './components/posts/post.list.component';  
  12. import { UserService } from './services/user.service';  
  13. import { AlbumListComponent } from './components/albums/album.list.component';  
  14. import { SearchComponent } from './components/filter/search.component';  
  15. import { APP_ROUTES } from './app.routes';  
  16. import { NgbdModalBasic } from './components/user/modal-basic';  
  17.   
  18. @NgModule({  
  19.   imports: [BrowserModule, FormsModule, HttpModule, RouterModule.forRoot(APP_ROUTES)],  
  20.   declarations: [SearchComponent, AlbumListComponent, TodoComponent, NavComponent, AppComponent, UserListComponent, PostListComponent],  
  21.   bootstrap: [AppComponent],  
  22.   providers: [UserService]  
  23. })  
  24. export class AppModule { }  

Output

Angular

Source code for point number #7

If you observe point number #5 and #6, I am loading Album and Todos list details using service call and injecting the service class to a component class constructor using dependency injection mechanism.

Source code for point number #8

search.component.html

  1. <div class="col-md-8">  
  2.   <div class="input-group">  
  3.     <input type="text" class="form-control" placeholder="Name" [(ngModel)]="searchFilter">  
  4.     <div class="input-group-btn">  
  5.       <button class="btn btn-success" type="button" (click)="searchUsers()">Go</button>  
  6.     </div>  
  7.     <div class="input-group-btn">  
  8.       <button class="btn btn-default" type="button" (click)="clear()">Clear</button>  
  9.     </div>  
  10.   </div>  
  11. </div> 

search.component.ts

  1. import {  
  2.   Component, Input, Output,  
  3.   OnInit, EventEmitter  
  4. } from '@angular/core';  
  5.   
  6. import { AlbumListComponent } from '../albums/album.list.component';  
  7. import { UserListComponent } from '../user/user.list.component';  
  8.   
  9. @Component({  
  10.   selector: 'search-component',  
  11.   templateUrl: 'app/components/filter/search.component.html',  
  12. })  
  13. export class SearchComponent implements OnInit {  
  14.   searchFilter: String;  
  15.   @Input('searchInput') searchInput: string = '';  
  16.   @Output() goClicked: EventEmitter<any> = new EventEmitter<any>();  
  17.   @Output() clearClicked: EventEmitter<any> = new EventEmitter<any>();  
  18.   
  19.   constructor() {  
  20.     /*private _albumListComponent: AlbumListComponent, private _userListComponent: UserListComponent*/  
  21.     console.log('I am constructor!');  
  22.   }  
  23.   
  24.   ngOnInit() {  
  25.   }  
  26.   
  27.   searchUsers() {  
  28.     console.log('searchUsers');  
  29.     this.goClicked.emit({  
  30.       searchText: this.searchFilter  
  31.     });  
  32.   }  
  33.   clear() {  
  34.     this.searchFilter = '';  
  35.     this.clearClicked.emit({  
  36.     });  
  37.   }  

app.module.ts

  1. import { NgModule } from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3. import { FormsModule } from '@angular/forms';  
  4. import { HttpModule } from '@angular/http';  
  5. import { RouterModule } from '@angular/router';  
  6.   
  7. import { AppComponent } from './app.component';  
  8. import { UserListComponent} from './components/user/user.list.component';  
  9. import { NavComponent } from './components/nav/nav.component';  
  10. import { SearchComponent } from './components/filter/search.component';  
  11. import { APP_ROUTES } from './app.routes';  
  12. import { NgbdModalBasic } from './components/user/modal-basic';  
  13.   
  14. @NgModule({  
  15.   imports: [BrowserModule, FormsModule, HttpModule, RouterModule.forRoot(APP_ROUTES)],  
  16.   declarations: [SearchComponent, NavComponent, AppComponent, UserListComponent],  
  17.   bootstrap: [AppComponent],  
  18.   providers: [UserService]  
  19. })  
  20. export class AppModule { } 

Output

Angular

Source code for point number #9

highlight.directive.ts

  1. import {  
  2.   Directive, ElementRef,  
  3.   Renderer, Input  
  4. } from '@angular/core';  
  5.   
  6. @Directive({  
  7.   selector: '[highlight]'  
  8. })  
  9. export class HighlightDirective {  
  10.   userData: any = {};  
  11.   
  12.   constructor(private _eleRef: ElementRef,  
  13.               private _renderer: Renderer) {  
  14.   }  
  15.   
  16.   @Input()  
  17.   set hover(obj: any) {  
  18.     this.userData = obj;  
  19.   }  
  20.   
  21.   /*ngOnInit() { 
  22.  
  23.   }*/  
  24.   ngAfterViewInit() {  
  25.     if ((this._eleRef.nativeElement.innerText.indexOf('.org') > 0) === true) {  
  26.       this._eleRef.nativeElement.style.color = 'red';  
  27.     }  
  28.   }  

hover.directive.ts

  1. import {  
  2.   Directive, ElementRef,  
  3.   HostListener, Renderer, Input  
  4. } from '@angular/core';  
  5.   
  6. @Directive({  
  7.   selector: '[hover]'  
  8. })  
  9. export class HoverDirective {  
  10.   userData: any = {};  
  11.   
  12.   constructor(private _eleRef: ElementRef,  
  13.               private _renderer: Renderer) {  
  14.   }  
  15.   
  16.   @Input() set hover(obj: any) {  
  17.     this.userData = obj;  
  18.   }  
  19.   
  20.   ngOnInit() {  
  21.     //if(this.userData.contains("Ervin"))  
  22.     //this._eleRef.nativeElement.style.color = 'red';  
  23.     this._eleRef.nativeElement.onclick = (event: Event) => {  
  24.       alert(JSON.stringify(this.userData));  
  25.     }  
  26.   }  
  27.   
  28.   @HostListener('mouseenter') onMouseEnter() {  
  29.     console.log('mouseenter'this._eleRef.nativeElement);  
  30.     this._eleRef.nativeElement.style.color = 'red';  
  31.     //this._renderer.setElementStyle(this._eleRef.nativeElement.nativeElement, 'color', 'red');  
  32.   }  
  33.   
  34.   @HostListener('mouseleave') onMouseLeave() {  
  35.     console.log('mouseleave'this._eleRef.nativeElement);  
  36.     this._eleRef.nativeElement.style.color = '';  
  37.     if ((this._eleRef.nativeElement.innerText.indexOf('.org') > 0) === true) {  
  38.       this._eleRef.nativeElement.style.color = 'red';  
  39.     }  
  40.   }  
  41. }  

user.list.component.html

  1. <div class="col-md-12">  
  2.   <section class="users" *ngIf="isDetailsView">  
  3.     <ul class="cards">  
  4.       <li *ngFor="let usr of filteredData" (click)="showUser(usr)" hover highlight>  
  5.         <p><strong>{{usr.name}}</strong></p>  
  6.         <em><a target="_blank" href="http://{{usr.website}}">{{usr.website}}</a></em>  
  7.         <p>Street: {{usr.address?.street}}</p>  
  8.         <p>suite: {{usr.address?.suite}}</p>  
  9.         <p>city: {{usr.address?.city}}</p>  
  10.         <p>zipcode: {{usr.address?.zipcode}}</p>  
  11.         <em><a target="_blank" href="http://{{usr.website}}">{{usr.website}}</a></em>  
  12.       </li>  
  13.     </ul>  
  14.   </section>  
  15. </div>  

app.module.ts

  1. import { NgModule } from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3. import { FormsModule } from '@angular/forms';  
  4. import { HttpModule } from '@angular/http';  
  5. import { RouterModule } from '@angular/router';  
  6. import { AppComponent } from './app.component';  
  7. import { UserListComponent} from './components/user/user.list.component';  
  8. import { NewUserComponent } from './components/user/new.user.component'  
  9. import { TodoComponent } from './components/todo/todo.component';  
  10. import { NavComponent } from './components/nav/nav.component';  
  11. import { PostListComponent } from './components/posts/post.list.component';  
  12. import { UserService } from './services/user.service';  
  13. import { HoverDirective } from './directives/hover.directive';  
  14. import { HighlightDirective } from './directives/highlight.directive';  
  15. import { UserComponent } from './components/user/user.component';  
  16. import { AlbumListComponent } from './components/albums/album.list.component';  
  17. import { SearchComponent } from './components/filter/search.component';  
  18. import { APP_ROUTES } from './app.routes';  
  19.   
  20. @NgModule({  
  21.   imports: [BrowserModule, FormsModule, HttpModule, RouterModule.forRoot(APP_ROUTES)],  
  22.   declarations: [SearchComponent, AlbumListComponent, NgbdModalBasic, NewUserComponent, TodoComponent, NavComponent, AppComponent, UserListComponent, PostListComponent, HoverDirective, HighlightDirective],  
  23.   bootstrap: [AppComponent],  
  24.   providers: [UserService]  
  25. })  
  26. export class AppModule { } 

Output

Angular

Source code for point number #10

new.user.component.html

  1. <div class="container">  
  2.   <div class="row">  
  3.     <form role="form" (ngSubmit)="submit($event)">  
  4.       <legend>New User</legend>  
  5.       <div class="form-group">  
  6.         <label for="fname">First Name</label>  
  7.         <input type="text" name="fname" required value="" class="form-control" [(ngModel)]="user.firstName">  
  8.       </div>  
  9.       <div class="form-group">  
  10.         <label for="mname">Middle Name</label>  
  11.         <input type="text" name="mname" value="" class="form-control" [(ngModel)]="user.middleName">  
  12.       </div>  
  13.   
  14.       <div class="form-group">  
  15.         <label for="lname">Last Name</label>  
  16.         <input type="text" name="lname" value="" required class="form-control" [(ngModel)]="user.lastName">  
  17.       </div>  
  18.       <div class="form-group">  
  19.         <label for="email">Email</label>  
  20.         <input type="email" name="email" value="" required class="form-control" [(ngModel)]="user.email">  
  21.       </div>  
  22.   
  23.       <div class="form-group">  
  24.         <label>Country</label>  
  25.         <select name="country" class="form-control" [(ngModel)]="user.country" required>  
  26.           <option [value]="0">Select</option>  
  27.           <option *ngFor="let c of countries" [value]="c.code">{{c.name}}</option>  
  28.         </select>  
  29.       </div>  
  30.       <button type="submit" class="btn btn-success">Submit</button>  
  31.       <span>{{user | json}}</span>  
  32.     </form>  
  33.   </div>  
  34.   <ngbd-modal-basic></ngbd-modal-basic>  
  35. </div>  

new.user.component.ts

  1. import { Component, OnInit } from '@angular/core';  
  2. import { COUNTRIES } from './country';  
  3.   
  4. @Component({  
  5.   moduleId: module.id,  
  6.   selector: 'new-user',  
  7.   templateUrl: 'new.user.component.html',  
  8.   styles: [`input.ng-invalid.ng-touched {  
  9.         border: 1px solid red;  
  10.     }  
  11.     select.ng-invalid.ng-touched {  
  12.         border: 1px solid red;  
  13.     }  
  14.   
  15.     input.ng-valid.ng-touched {  
  16.         border: 1px solid green;  
  17.     }  
  18.     select.ng-valid.ng-touched {  
  19.         border: 1px solid green;  
  20.     }  
  21.     `]  
  22. })  
  23. export class NewUserComponent implements OnInit {  
  24.   user: User;  
  25.   countries: any[];  
  26.   
  27.   constructor() {  
  28.     this.user = new User();  
  29.   }  
  30.   
  31.   ngOnInit() {  
  32.     this.countries = COUNTRIES;  
  33.   }  
  34.   
  35.   submit(event: Event) {  
  36.     console.log(this.user);  
  37.   }  
  38. }  
  39.   
  40. class User {  
  41.   firstName: string;  
  42.   middleName: String;  
  43.   lastName: String;  
  44.   email: String;  
  45.   country: String;  

app.module.ts

  1. import { NgModule } from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3. import { FormsModule } from '@angular/forms';  
  4. import { HttpModule } from '@angular/http';  
  5. import { RouterModule } from '@angular/router';  
  6.   
  7. import { AppComponent } from './app.component';  
  8. import { UserListComponent} from './components/user/user.list.component';  
  9. import { NewUserComponent } from './components/user/new.user.component'  
  10. import { TodoComponent } from './components/todo/todo.component';  
  11. import { NavComponent } from './components/nav/nav.component';  
  12. import { PostListComponent } from './components/posts/post.list.component';  
  13. import { UserService } from './services/user.service';  
  14. import { HighlightDirective } from './directives/highlight.directive';  
  15. import { UserComponent } from './components/user/user.component';  
  16. import { AlbumListComponent } from './components/albums/album.list.component';  
  17. import { SearchComponent } from './components/filter/search.component';  
  18. import { APP_ROUTES } from './app.routes';  
  19.   
  20. @NgModule({  
  21.   imports: [BrowserModule, FormsModule, HttpModule, RouterModule.forRoot(APP_ROUTES)],  
  22.   declarations: [SearchComponent, AlbumListComponent, NgbdModalBasic,, NewUserComponent, TodoComponent, NavComponent, AppComponent, UserListComponent, PostListComponent, HighlightDirective],  
  23.   bootstrap: [AppComponent],  
  24.   providers: [UserService]  
  25. })  
  26. export class AppModule { }  

Output

Angular

Angular

Source code for point number #11

package.json

  1. {  
  2.   "name""angular-quickstart",  
  3.   "version""1.0.0",  
  4.     ---------------------------  
  5.     ---------------------------  
  6.     ---------------------------  
  7.   "keywords": [],  
  8.   "author""",  
  9.   "license""MIT",  
  10.   "dependencies": {  
  11.     -----------------------------  
  12.     -----------------------------  
  13.     -----------------------------  
  14.     "@ng-bootstrap/ng-bootstrap""^1.0.0",  
  15.     "bootstrap""^4.0.0-beta.3",  
  16.     -----------------------------  
  17.     -----------------------------  
  18.     -----------------------------  
  19.   },  
  20.   "devDependencies": {  
  21.     ------------  
  22.     ------------  
  23.     ------------  
  24.   "repository": {}  
  25. }  

app.module.ts

  1. import { NgModule } from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3. import { FormsModule } from '@angular/forms';  
  4. import { HttpModule } from '@angular/http';  
  5. import { RouterModule } from '@angular/router';  
  6.   
  7. import { AppComponent } from './app.component';  
  8. import { UserListComponent} from './components/user/user.list.component';  
  9. import { NewUserComponent } from './components/user/new.user.component'  
  10. import { TodoComponent } from './components/todo/todo.component';  
  11. import { NavComponent } from './components/nav/nav.component';  
  12. import { PostListComponent } from './components/posts/post.list.component';  
  13. import { UserService } from './services/user.service';  
  14. import { HoverDirective } from './directives/hover.directive';  
  15. import { HighlightDirective } from './directives/highlight.directive';  
  16. import { UserComponent } from './components/user/user.component';  
  17. import { AlbumListComponent } from './components/albums/album.list.component';  
  18. import { SearchComponent } from './components/filter/search.component';  
  19. import { APP_ROUTES } from './app.routes';  
  20. import {NgbModule} from '@ng-bootstrap/ng-bootstrap';  
  21. import { NgbdModalBasic } from './components/user/modal-basic';  
  22.   
  23. @NgModule({  
  24.   imports: [NgbModule.forRoot(), BrowserModule, FormsModule, HttpModule, RouterModule.forRoot(APP_ROUTES)],  
  25.   declarations: [SearchComponent, AlbumListComponent, NgbdModalBasic, UserComponent , NewUserComponent, TodoComponent, NavComponent, AppComponent, UserListComponent, PostListComponent, HoverDirective, HighlightDirective],  
  26.   bootstrap: [AppComponent],  
  27.   providers: [UserService]  
  28. })  
  29. export class AppModule { }  

Source code for point number #13

Angular

Finally the app.router.ts fie looks as below

app.routes.ts

  1. import { Routes } from '@angular/router';  
  2. import { UserListComponent } from './components/user/user.list.component';  
  3. import { NewUserComponent } from './components/user/new.user.component';  
  4. import { TodoComponent } from './components/todo/todo.component';  
  5. import { UserComponent } from './components/user/user.component';  
  6. import { AlbumListComponent } from './components/albums/album.list.component';  
  7. export const APP_ROUTES: Routes = [  
  8.   {  
  9.     path: '', component: UserListComponent  
  10.   },  
  11.   {  
  12.     path: 'users',  
  13.     children: [  
  14.       {  
  15.         path: 'new', component: NewUserComponent,  
  16.       },  
  17.       {  
  18.         path: '', component: UserListComponent  
  19.       }  
  20.     ]  
  21.   },  
  22.   {  
  23.     path: 'user/:id', component: UserComponent  
  24.   },  
  25.   {  
  26.     path: 'todos',  
  27.     component: TodoComponent  
  28.   },  
  29.   {  
  30.     path: 'todos/:id', component: TodoComponent  
  31.   },  
  32.   {  
  33.     path: 'albums',  
  34.     component: AlbumListComponent  
  35.   },  
  36.   {  
  37.     path: 'albums/:id', component: AlbumListComponent  
  38.   }  
  39. ];  

Please find the complete source code in zip format, you can download and play around with it.

Steps to run the code

Step #1 - npm install

Step #2 - npm start

More articles on angular

I would appreciate your valuable comments. 

G
M
T
 
Text-to-speech function is limited to 200 characters

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now