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:
- Create an angular application by following quick start
- Create a component ‘nav.component’ with application title and navigation links.
- Navigation Links
- Users
- Todos
- Albums
- The navigation menu should be available on every page and corresponding menu items should be highlighted when you visit a route.
- Create a component named ‘user.list.component’ which shows information about users.
- 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.
- Demonstrate *ngFor directive with li’s/tr’s
- Demonstrate ngClass, ngModel
- Demonstrate interpolation and two-way binding
- Demonstrate *ngIf. Show ‘No Data’ message there is data is available.
- Create a component named ‘post.list.component’ which shows user posts when a userid parameter is sent.
- 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.
- 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
- All services should follow these rules
- Demonstrate rxjs observables
- Error handling
- Dependency Injection (Inject the service where ever required)
- Create a component named ‘search.component’ which helps a user to perform search operations
- It should have input[type=text], ‘search’ button and ‘clear’ button.
- On clicking ‘search’, component should emit an event with search criteria to parent component
- Use search component in the user list and album list components.
- Search component label should change to ‘user’ or ‘album’ based on the type of parent component.
- 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.
- Demonstrate form validation with angular by creating a new user registration page.
- A new button on ‘user.list.component’ should navigate to a new route (user/new)
- Create a user, address classes and bind them to create a registration page.
- 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*
- 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)
- The template layouts (HTML design) is up to your creativity.
- Organize your code in the following folder structure
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,
Source code for point number #2
nav.component.html
- <!-- Static navbar -->
- <nav class="navbar navbar-default">
- <div class="container">
- <div class="navbar-header">
- <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
- <span class="sr-only">Toggle navigation</span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- </button>
- <a class="navbar-brand" href="#">Anguar2 Sample</a>
- </div>
- <div id="navbar" class="navbar-collapse collapse">
- <ul class="nav navbar-nav">
- <li [routerLinkActive]="['active']" class="active"><a routerLink="/users" href="#">Users</a></li>
- <li [routerLinkActive]="['active']"><a routerLink="/todos" href="# ">Todos</a></li>
- <li [routerLinkActive]="['active']"><a routerLink="/albums" href="# ">Albums</a></li>
- </ul>
- </div>
- <!--/.nav-collapse -->
- </div>
- <!--/.container-fluid -->
- </nav>
nav.component.ts
- import { Component, OnInit } from '@angular/core';
-
-
- @Component({
- moduleId: module.id,
- selector: 'navmenu',
- templateUrl: 'nav.component.html'
- })
- export class NavComponent implements OnInit {
- constructor() { }
- ngOnInit() { }
- }
app.module.ts
- import { NgModule } from '@angular/core';
- import { BrowserModule } from '@angular/platform-browser';
- import { FormsModule } from '@angular/forms';
- import { HttpModule } from '@angular/http';
- import { RouterModule } from '@angular/router';
- import { AppComponent } from './app.component';
- import { NavComponent } from './components/nav/nav.component';
-
- @NgModule({
- imports: [NgbModule.forRoot(), BrowserModule, FormsModule, HttpModule, RouterModule.forRoot(APP_ROUTES)],
- declarations: [NavComponent, AppComponent],
- bootstrap: [AppComponent],
- providers: [UserService]
- })
- export class AppModule { }
app.component.ts
- import { Component } from '@angular/core';
- @Component({
- selector: 'my-app',
- template: `<navmenu></navmenu>
- <router-outlet></router-outlet>
- `
- })
- export class AppComponent {
- ChildEvent(event: any) {
- console.log(event);
- }
- }
Output
Source code for point number #3
user.list.component.css
- ul {
- list-style-type: none;
- margin: 0;
- padding: 0;
- }
-
- ul.cards>li {
- padding: 5px;
- cursor: pointer;
- margin: 10px;
- width: 200px;
- height: 300px;
- vertical-align: top;
- border: 1px solid #ccc;
- box-shadow: 10px 10px 5px #CCC;
- display: inline-block;
- }
-
- ul.cards>li:hover {
- border: 1px solid deepskyblue;
- box-shadow: 15px 15px 5px #CCC;
- }
-
- section.users {
- padding: 5px;
- }
user.list.component.html
- <div class="container">
- <div class="row">
- <div class="col-md-7">
- <search-component (goClicked)="searchTriggered($event)" (clearClicked)="clearTriggered($event)"></search-component>
- </div>
- <div class="col-md-3">
- <div class="btn-group pull-right">
- <button type="button" class="btn" [ngClass]="!isDetailsView ? 'btn btn-success' : 'btn'" (click)="toggle(false)">List</button>
- <button type="button" class="btn" [ngClass]="isDetailsView ? 'btn btn-success' : 'btn'" (click)="toggle(true)">Detail</button>
- </div>
- </div>
- <div class="col-md-2">
- <a routerLink="/users/new" href="#" class="btn btn-success">New</a>
- </div>
- </div>
- <div class="row">
- <div class="col-md-12">
- <section class="users">
- <table class="table table-bordered table-hover" *ngIf="!isDetailsView">
- <thead>
- <tr>
- <td><strong>Name</strong></td>
- <td><strong>Email</strong></td>
- <td><strong>Phone</strong></td>
- <td><strong>Website</strong></td>
- </tr>
- </thead>
- <tbody>
- <tr *ngFor="let usr of filteredData">
- <td>{{usr.name}}</td>
- <td>{{usr.email}}</td>
- <td>{{usr.phone | uppercase}}</td>
- <td>
- <a target="_blank" href="http://{{usr.website}}">{{usr.website}}</a>
- </td>
- </tr>
- </tbody>
- <tbody *ngIf="filteredData.length === 0">
- <tr>
- <td colspan="4">
- <h1>No Data!</h1>
- </td>
- </tr>
- </tbody>
- </table>
- </section>
- </div>
- </div>
- <div class="row">
- <div class="col-md-12">
- <section class="users" *ngIf="isDetailsView">
- <ul class="cards">
- <li *ngFor="let usr of filteredData" (click)="showUser(usr)" hover highlight>
- <p><strong>{{usr.name}}</strong></p>
- <em><a target="_blank" href="http://{{usr.website}}">{{usr.website}}</a></em>
- <p>Street: {{usr.address?.street}}</p>
- <p>suite: {{usr.address?.suite}}</p>
- <p>city: {{usr.address?.city}}</p>
- <p>zipcode: {{usr.address?.zipcode}}</p>
- <em><a target="_blank" href="http://{{usr.website}}">{{usr.website}}</a></em>
- </li>
- </ul>
- </section>
- </div>
- </div>
- </div>
user.list.component.ts
- import {
- Component, Input,
- OnInit
- } from '@angular/core';
- import { UserService } from '../../services/user.service';
-
- import { Router } from '@angular/router';
-
- @Component({
- selector: 'user-list',
- templateUrl: 'app/components/user/user.list.component.html',
- styleUrls: ['app/components/user/user.list.component.css']
- })
- export class UserListComponent implements OnInit {
- @Input('userdata') users: any[] = [];
-
- searchFilter: string = '';
- isDetailsView: boolean = true;
- filteredData: any[];
-
- constructor(private _userService: UserService, private _router: Router) {
- console.log('I am constructor!');
- }
-
- toggle(isDetailsView: any) {
- console.log(isDetailsView);
- this.isDetailsView = isDetailsView;
- }
-
- ngOnInit() {
- this._userService.getUsers().subscribe((users) => {
- this.filteredData = this.users = users;
- }, error => {
- console.error('Error in UserList', error);
- });
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- clear() {
- this.searchFilter = '';
- this.filteredData = this.users;
- }
-
- showUser(user: any) {
- this._router.navigate(['/user', user.id]);
- }
-
- clearTriggered(){
-
- this.filteredData = this.users;
- }
-
- searchTriggered(data: any) {
- console.log('user list search button click event');
- this.filteredData = this.users.filter((item) => {
- return item.name.toLowerCase().indexOf(data.searchText.toLowerCase()) > -1;
- });
- }
- }
user.component.ts
- import { Component, OnInit } from '@angular/core';
- import { ActivatedRoute } from '@angular/router';
- import { UserService } from '../../services/user.service';
-
- @Component({
- moduleId: module.id,
- selector: 'user',
- providers: [UserService],
- template: `
- <a routerLink="/users">Back to Users</a>
- <hr>
- <ul class="cards">
- <li>
- <p><strong>{{usr.name}}</strong></p>
- <p>Street: {{usr.address?.street}}</p>
- <p>suite: {{usr.address?.suite}}</p>
- <p>city: {{usr.address?.city}}</p>
- <p>zipcode: {{usr.address?.zipcode}}</p>
- <em><a target="_blank" href="http://{{usr.website}}">{{usr.website}}</a></em>
- </li>
- </ul>
- `
- })
- export class UserComponent implements OnInit {
- usr: any = {};
- constructor(private aroute: ActivatedRoute,
- private _userService: UserService) { }
-
- ngOnInit() {
- this.aroute.params.subscribe((params) => {
- let userId = params['id'];
- this._userService.getUser(userId).subscribe((user) => {
- this.usr = user;
- });
- });
- }
- }
app.module.ts
- import { NgModule } from '@angular/core';
- import { BrowserModule } from '@angular/platform-browser';
- import { FormsModule } from '@angular/forms';
- import { HttpModule } from '@angular/http';
- import { RouterModule } from '@angular/router';
-
- import { AppComponent } from './app.component';
- import { UserListComponent} from './components/user/user.list.component';
- import { NavComponent } from './components/nav/nav.component';
- import { SearchComponent } from './components/filter/search.component';
- import { APP_ROUTES } from './app.routes';
- import { UserComponent } from './components/user/user.component';
- import { UserService } from './services/user.service';
-
-
- @NgModule({
- imports: [BrowserModule, FormsModule, HttpModule, RouterModule.forRoot(APP_ROUTES)],
- declarations: [SearchComponent, NavComponent, AppComponent, UserListComponent, UserComponent
- ],
- bootstrap: [AppComponent],
- providers: [UserService]
- })
- export class AppModule { }
Output
When we click on Users then by default it is the Detail, output as below,
If we click on List view then below is the output,
Source code for point number #4
post.list.component.ts
- import { Component } from '@angular/core';
- import { UserService } from '../../services/user.service';
-
- @Component({
- selector: 'post-list',
- template: `Yet to..`
- })
- export class PostListComponent {
- constructor(private _userService: UserService) {}
-
- ngOnInit() {
- this._userService.getUsers()
- .subscribe((data) => {
- console.log(data);
- });
- }
- }
app.module.ts
- import { NgModule } from '@angular/core';
- import { BrowserModule } from '@angular/platform-browser';
- import { FormsModule } from '@angular/forms';
- import { HttpModule } from '@angular/http';
- import { RouterModule } from '@angular/router';
-
- import { AppComponent } from './app.component';
- import { UserListComponent} from './components/user/user.list.component';
- import { NewUserComponent } from './components/user/new.user.component'
- import { TodoComponent } from './components/todo/todo.component';
- import { NavComponent } from './components/nav/nav.component';
- import { PostListComponent } from './components/posts/post.list.component';
- import { UserService } from './services/user.service';
- import { SearchComponent } from './components/filter/search.component';
- import { APP_ROUTES } from './app.routes';
- import { NgbdModalBasic } from './components/user/modal-basic';
-
- @NgModule({
- imports: [BrowserModule, FormsModule, HttpModule, RouterModule.forRoot(APP_ROUTES)],
- declarations: [SearchComponent, NavComponent, AppComponent, UserListComponent, PostListComponent],
- bootstrap: [AppComponent],
- providers: [UserService]
- })
- export class AppModule { }
Source code for point number #5
album.list.component.html
- <div class="container">
- <div class="row">
- <search-component (goClicked)="searchTriggered($event)" (clearClicked)="clearTriggered($event)"></search-component>
- </div>
- <div class="row">
- <div *ngFor="let album of albumlist">
- <div class="alert">
- <strong>{{album.userId}}</strong> {{album.title}}
- </div>
- </div>
- </div>
- </div>
album.list.component.ts
- import { Component, Input } from '@angular/core';
- import { AlbumService } from '../../services/album.service';
-
- import { ActivatedRoute } from '@angular/router';
-
- @Component({
- moduleId: module.id,
- selector: 'album-list',
- templateUrl: 'album.list.component.html',
- providers: [AlbumService]
- })
- export class AlbumListComponent {
- @Input('albumlist') _albumlist: any[] = [];
- albumlist: any[];
- constructor(private _albumService: AlbumService,
- private aroute: ActivatedRoute) {
-
- }
-
- ngOnInit() {
- this.aroute.params.subscribe((data) => {
- let userid = data['id'];
- console.log(userid);
- if (userid) {
- this._albumService.getAlbumByUserId(userid).subscribe((data) => {
- this.albumlist = data;
- console.log(data);
- });
- } else {
- this._albumService.getAlbums().subscribe((data) => {
- this.albumlist = this._albumlist = data;
- });
- }
-
- });
- }
- clearTriggered() {
- this.albumlist = this._albumlist;
- }
- searchTriggered(data: any) {
- console.log('album list search button click event');
- this.albumlist = this.albumlist.filter((item) => {
- return item.title.toLowerCase().indexOf(data.searchText.toLowerCase()) > -1;
- });
- }
- }
album.service.ts
- import { Injectable } from '@angular/core';
- import { Http } from '@angular/http';
- import 'rxjs/add/operator/map';
-
- @Injectable()
- export class AlbumService {
- url: string = 'https://jsonplaceholder.typicode.com/';
- constructor(private _http: Http) { }
-
- getAlbums() {
- let albumUrl = this.url + 'albums';
- return this._http.get(albumUrl)
- .map((res) => { return res.json(); });
- }
-
- getAlbumByUserId(id: number) {
- let albumUrl = `${this.url}albums`;
- return this._http.get(albumUrl + '?userId=' + id)
- .map((res) => { return res.json(); });
- }
- }
app.module.ts
- import { NgModule } from '@angular/core';
- import { BrowserModule } from '@angular/platform-browser';
- import { FormsModule } from '@angular/forms';
- import { HttpModule } from '@angular/http';
- import { RouterModule } from '@angular/router';
- import { AppComponent } from './app.component';
- import { UserListComponent} from './components/user/user.list.component';
- import { TodoComponent } from './components/todo/todo.component';
- import { NavComponent } from './components/nav/nav.component';
- import { PostListComponent } from './components/posts/post.list.component';
- import { UserService } from './services/user.service';
- import { AlbumListComponent } from './components/albums/album.list.component';
- import { SearchComponent } from './components/filter/search.component';
- import { APP_ROUTES } from './app.routes';
- import { NgbdModalBasic } from './components/user/modal-basic';
-
- @NgModule({
- imports: [BrowserModule, FormsModule, HttpModule, RouterModule.forRoot(APP_ROUTES)],
- declarations: [SearchComponent, AlbumListComponent, TodoComponent, NavComponent, AppComponent, UserListComponent, PostListComponent],
- bootstrap: [AppComponent],
- providers: [UserService]
- })
- export class AppModule { }
Output
Source code for point number #6
todo.component.html
- <div class="container">
- <div class="row">
- <div *ngFor="let todo of todos">
- <div class="alert">
- <strong>{{todo.userId}}</strong> {{todo.title}}
- </div>
- </div>
- </div>
- </div>
todo.component.ts
- import { Component, OnInit } from '@angular/core';
- import { TodoService } from '../../services/todo.service';
- import { ActivatedRoute } from '@angular/router';
-
- @Component({
- moduleId: module.id,
- selector: 'todo',
- templateUrl: 'todo.component.html',
- providers: [TodoService]
- })
- export class TodoComponent implements OnInit {
- todos: any[];
- constructor(private _todoService: TodoService,
- private aroute: ActivatedRoute) {
-
- }
-
- ngOnInit() {
- this.aroute.params.subscribe((data) => {
- let userid = data['id'];
- console.log(userid);
- if (userid) {
- this._todoService.getTodosByUserId(userid).subscribe((data) => {
- this.todos = data;
- console.log(data);
- });
- } else {
- this._todoService.getTodos().subscribe((data) => {
- this.todos = data;
- });
- }
-
- });
-
- }
- }
todo.service.ts
- import { Injectable } from '@angular/core';
- import { Http } from '@angular/http';
- import 'rxjs/add/operator/map';
-
- @Injectable()
- export class TodoService {
- url: string = 'https://jsonplaceholder.typicode.com/';
- constructor(private _http: Http) { }
-
- getTodos() {
- let todoUrl = this.url + 'todos';
- return this._http.get(todoUrl)
- .map((res) => { return res.json(); });
- }
-
- getTodosByUserId(id: number) {
- let todoUrl = `${this.url}todos`;
- return this._http.get(todoUrl + '?userId=' + id)
- .map((res) => { return res.json(); });
- }
- }
app.module.ts
- import { NgModule } from '@angular/core';
- import { BrowserModule } from '@angular/platform-browser';
- import { FormsModule } from '@angular/forms';
- import { HttpModule } from '@angular/http';
- import { RouterModule } from '@angular/router';
- import { AppComponent } from './app.component';
- import { UserListComponent} from './components/user/user.list.component';
- import { NewUserComponent } from './components/user/new.user.component'
- import { TodoComponent } from './components/todo/todo.component';
- import { NavComponent } from './components/nav/nav.component';
- import { PostListComponent } from './components/posts/post.list.component';
- import { UserService } from './services/user.service';
- import { AlbumListComponent } from './components/albums/album.list.component';
- import { SearchComponent } from './components/filter/search.component';
- import { APP_ROUTES } from './app.routes';
- import { NgbdModalBasic } from './components/user/modal-basic';
-
- @NgModule({
- imports: [BrowserModule, FormsModule, HttpModule, RouterModule.forRoot(APP_ROUTES)],
- declarations: [SearchComponent, AlbumListComponent, TodoComponent, NavComponent, AppComponent, UserListComponent, PostListComponent],
- bootstrap: [AppComponent],
- providers: [UserService]
- })
- export class AppModule { }
Output
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
- <div class="col-md-8">
- <div class="input-group">
- <input type="text" class="form-control" placeholder="Name" [(ngModel)]="searchFilter">
- <div class="input-group-btn">
- <button class="btn btn-success" type="button" (click)="searchUsers()">Go</button>
- </div>
- <div class="input-group-btn">
- <button class="btn btn-default" type="button" (click)="clear()">Clear</button>
- </div>
- </div>
- </div>
search.component.ts
- import {
- Component, Input, Output,
- OnInit, EventEmitter
- } from '@angular/core';
-
- import { AlbumListComponent } from '../albums/album.list.component';
- import { UserListComponent } from '../user/user.list.component';
-
- @Component({
- selector: 'search-component',
- templateUrl: 'app/components/filter/search.component.html',
- })
- export class SearchComponent implements OnInit {
- searchFilter: String;
- @Input('searchInput') searchInput: string = '';
- @Output() goClicked: EventEmitter<any> = new EventEmitter<any>();
- @Output() clearClicked: EventEmitter<any> = new EventEmitter<any>();
-
- constructor() {
-
- console.log('I am constructor!');
- }
-
- ngOnInit() {
- }
-
- searchUsers() {
- console.log('searchUsers');
- this.goClicked.emit({
- searchText: this.searchFilter
- });
- }
- clear() {
- this.searchFilter = '';
- this.clearClicked.emit({
- });
- }
- }
app.module.ts
- import { NgModule } from '@angular/core';
- import { BrowserModule } from '@angular/platform-browser';
- import { FormsModule } from '@angular/forms';
- import { HttpModule } from '@angular/http';
- import { RouterModule } from '@angular/router';
-
- import { AppComponent } from './app.component';
- import { UserListComponent} from './components/user/user.list.component';
- import { NavComponent } from './components/nav/nav.component';
- import { SearchComponent } from './components/filter/search.component';
- import { APP_ROUTES } from './app.routes';
- import { NgbdModalBasic } from './components/user/modal-basic';
-
- @NgModule({
- imports: [BrowserModule, FormsModule, HttpModule, RouterModule.forRoot(APP_ROUTES)],
- declarations: [SearchComponent, NavComponent, AppComponent, UserListComponent],
- bootstrap: [AppComponent],
- providers: [UserService]
- })
- export class AppModule { }
Output
Source code for point number #9
highlight.directive.ts
- import {
- Directive, ElementRef,
- Renderer, Input
- } from '@angular/core';
-
- @Directive({
- selector: '[highlight]'
- })
- export class HighlightDirective {
- userData: any = {};
-
- constructor(private _eleRef: ElementRef,
- private _renderer: Renderer) {
- }
-
- @Input()
- set hover(obj: any) {
- this.userData = obj;
- }
-
-
-
-
- ngAfterViewInit() {
- if ((this._eleRef.nativeElement.innerText.indexOf('.org') > 0) === true) {
- this._eleRef.nativeElement.style.color = 'red';
- }
- }
- }
hover.directive.ts
- import {
- Directive, ElementRef,
- HostListener, Renderer, Input
- } from '@angular/core';
-
- @Directive({
- selector: '[hover]'
- })
- export class HoverDirective {
- userData: any = {};
-
- constructor(private _eleRef: ElementRef,
- private _renderer: Renderer) {
- }
-
- @Input() set hover(obj: any) {
- this.userData = obj;
- }
-
- ngOnInit() {
-
-
- this._eleRef.nativeElement.onclick = (event: Event) => {
- alert(JSON.stringify(this.userData));
- }
- }
-
- @HostListener('mouseenter') onMouseEnter() {
- console.log('mouseenter', this._eleRef.nativeElement);
- this._eleRef.nativeElement.style.color = 'red';
-
- }
-
- @HostListener('mouseleave') onMouseLeave() {
- console.log('mouseleave', this._eleRef.nativeElement);
- this._eleRef.nativeElement.style.color = '';
- if ((this._eleRef.nativeElement.innerText.indexOf('.org') > 0) === true) {
- this._eleRef.nativeElement.style.color = 'red';
- }
- }
- }
user.list.component.html
- <div class="col-md-12">
- <section class="users" *ngIf="isDetailsView">
- <ul class="cards">
- <li *ngFor="let usr of filteredData" (click)="showUser(usr)" hover highlight>
- <p><strong>{{usr.name}}</strong></p>
- <em><a target="_blank" href="http://{{usr.website}}">{{usr.website}}</a></em>
- <p>Street: {{usr.address?.street}}</p>
- <p>suite: {{usr.address?.suite}}</p>
- <p>city: {{usr.address?.city}}</p>
- <p>zipcode: {{usr.address?.zipcode}}</p>
- <em><a target="_blank" href="http://{{usr.website}}">{{usr.website}}</a></em>
- </li>
- </ul>
- </section>
- </div>
app.module.ts
- import { NgModule } from '@angular/core';
- import { BrowserModule } from '@angular/platform-browser';
- import { FormsModule } from '@angular/forms';
- import { HttpModule } from '@angular/http';
- import { RouterModule } from '@angular/router';
- import { AppComponent } from './app.component';
- import { UserListComponent} from './components/user/user.list.component';
- import { NewUserComponent } from './components/user/new.user.component'
- import { TodoComponent } from './components/todo/todo.component';
- import { NavComponent } from './components/nav/nav.component';
- import { PostListComponent } from './components/posts/post.list.component';
- import { UserService } from './services/user.service';
- import { HoverDirective } from './directives/hover.directive';
- import { HighlightDirective } from './directives/highlight.directive';
- import { UserComponent } from './components/user/user.component';
- import { AlbumListComponent } from './components/albums/album.list.component';
- import { SearchComponent } from './components/filter/search.component';
- import { APP_ROUTES } from './app.routes';
-
- @NgModule({
- imports: [BrowserModule, FormsModule, HttpModule, RouterModule.forRoot(APP_ROUTES)],
- declarations: [SearchComponent, AlbumListComponent, NgbdModalBasic, NewUserComponent, TodoComponent, NavComponent, AppComponent, UserListComponent, PostListComponent, HoverDirective, HighlightDirective],
- bootstrap: [AppComponent],
- providers: [UserService]
- })
- export class AppModule { }
Output
Source code for point number #10
new.user.component.html
- <div class="container">
- <div class="row">
- <form role="form" (ngSubmit)="submit($event)">
- <legend>New User</legend>
- <div class="form-group">
- <label for="fname">First Name</label>
- <input type="text" name="fname" required value="" class="form-control" [(ngModel)]="user.firstName">
- </div>
- <div class="form-group">
- <label for="mname">Middle Name</label>
- <input type="text" name="mname" value="" class="form-control" [(ngModel)]="user.middleName">
- </div>
-
- <div class="form-group">
- <label for="lname">Last Name</label>
- <input type="text" name="lname" value="" required class="form-control" [(ngModel)]="user.lastName">
- </div>
- <div class="form-group">
- <label for="email">Email</label>
- <input type="email" name="email" value="" required class="form-control" [(ngModel)]="user.email">
- </div>
-
- <div class="form-group">
- <label>Country</label>
- <select name="country" class="form-control" [(ngModel)]="user.country" required>
- <option [value]="0">Select</option>
- <option *ngFor="let c of countries" [value]="c.code">{{c.name}}</option>
- </select>
- </div>
- <button type="submit" class="btn btn-success">Submit</button>
- <span>{{user | json}}</span>
- </form>
- </div>
- <ngbd-modal-basic></ngbd-modal-basic>
- </div>
new.user.component.ts
- import { Component, OnInit } from '@angular/core';
- import { COUNTRIES } from './country';
-
- @Component({
- moduleId: module.id,
- selector: 'new-user',
- templateUrl: 'new.user.component.html',
- styles: [`input.ng-invalid.ng-touched {
- border: 1px solid red;
- }
- select.ng-invalid.ng-touched {
- border: 1px solid red;
- }
-
- input.ng-valid.ng-touched {
- border: 1px solid green;
- }
- select.ng-valid.ng-touched {
- border: 1px solid green;
- }
- `]
- })
- export class NewUserComponent implements OnInit {
- user: User;
- countries: any[];
-
- constructor() {
- this.user = new User();
- }
-
- ngOnInit() {
- this.countries = COUNTRIES;
- }
-
- submit(event: Event) {
- console.log(this.user);
- }
- }
-
- class User {
- firstName: string;
- middleName: String;
- lastName: String;
- email: String;
- country: String;
- }
app.module.ts
- import { NgModule } from '@angular/core';
- import { BrowserModule } from '@angular/platform-browser';
- import { FormsModule } from '@angular/forms';
- import { HttpModule } from '@angular/http';
- import { RouterModule } from '@angular/router';
-
- import { AppComponent } from './app.component';
- import { UserListComponent} from './components/user/user.list.component';
- import { NewUserComponent } from './components/user/new.user.component'
- import { TodoComponent } from './components/todo/todo.component';
- import { NavComponent } from './components/nav/nav.component';
- import { PostListComponent } from './components/posts/post.list.component';
- import { UserService } from './services/user.service';
- import { HighlightDirective } from './directives/highlight.directive';
- import { UserComponent } from './components/user/user.component';
- import { AlbumListComponent } from './components/albums/album.list.component';
- import { SearchComponent } from './components/filter/search.component';
- import { APP_ROUTES } from './app.routes';
-
- @NgModule({
- imports: [BrowserModule, FormsModule, HttpModule, RouterModule.forRoot(APP_ROUTES)],
- declarations: [SearchComponent, AlbumListComponent, NgbdModalBasic,, NewUserComponent, TodoComponent, NavComponent, AppComponent, UserListComponent, PostListComponent, HighlightDirective],
- bootstrap: [AppComponent],
- providers: [UserService]
- })
- export class AppModule { }
Output
Source code for point number #11
package.json
- {
- "name": "angular-quickstart",
- "version": "1.0.0",
- ---------------------------
- ---------------------------
- ---------------------------
- "keywords": [],
- "author": "",
- "license": "MIT",
- "dependencies": {
- -----------------------------
- -----------------------------
- -----------------------------
- "@ng-bootstrap/ng-bootstrap": "^1.0.0",
- "bootstrap": "^4.0.0-beta.3",
- -----------------------------
- -----------------------------
- -----------------------------
- },
- "devDependencies": {
- ------------
- ------------
- ------------
- "repository": {}
- }
app.module.ts
- import { NgModule } from '@angular/core';
- import { BrowserModule } from '@angular/platform-browser';
- import { FormsModule } from '@angular/forms';
- import { HttpModule } from '@angular/http';
- import { RouterModule } from '@angular/router';
-
- import { AppComponent } from './app.component';
- import { UserListComponent} from './components/user/user.list.component';
- import { NewUserComponent } from './components/user/new.user.component'
- import { TodoComponent } from './components/todo/todo.component';
- import { NavComponent } from './components/nav/nav.component';
- import { PostListComponent } from './components/posts/post.list.component';
- import { UserService } from './services/user.service';
- import { HoverDirective } from './directives/hover.directive';
- import { HighlightDirective } from './directives/highlight.directive';
- import { UserComponent } from './components/user/user.component';
- import { AlbumListComponent } from './components/albums/album.list.component';
- import { SearchComponent } from './components/filter/search.component';
- import { APP_ROUTES } from './app.routes';
- import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
- import { NgbdModalBasic } from './components/user/modal-basic';
-
- @NgModule({
- imports: [NgbModule.forRoot(), BrowserModule, FormsModule, HttpModule, RouterModule.forRoot(APP_ROUTES)],
- declarations: [SearchComponent, AlbumListComponent, NgbdModalBasic, UserComponent , NewUserComponent, TodoComponent, NavComponent, AppComponent, UserListComponent, PostListComponent, HoverDirective, HighlightDirective],
- bootstrap: [AppComponent],
- providers: [UserService]
- })
- export class AppModule { }
Source code for point number #13
Finally the app.router.ts fie looks as below
app.routes.ts
- import { Routes } from '@angular/router';
- import { UserListComponent } from './components/user/user.list.component';
- import { NewUserComponent } from './components/user/new.user.component';
- import { TodoComponent } from './components/todo/todo.component';
- import { UserComponent } from './components/user/user.component';
- import { AlbumListComponent } from './components/albums/album.list.component';
- export const APP_ROUTES: Routes = [
- {
- path: '', component: UserListComponent
- },
- {
- path: 'users',
- children: [
- {
- path: 'new', component: NewUserComponent,
- },
- {
- path: '', component: UserListComponent
- }
- ]
- },
- {
- path: 'user/:id', component: UserComponent
- },
- {
- path: 'todos',
- component: TodoComponent
- },
- {
- path: 'todos/:id', component: TodoComponent
- },
- {
- path: 'albums',
- component: AlbumListComponent
- },
- {
- path: 'albums/:id', component: AlbumListComponent
- }
- ];
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.
| | | | | | | | | |
Text-to-speech function is limited to 200 characters