Angular 6 – AppDividend https://appdividend.com Latest Code Tutorials Tue, 23 Oct 2018 09:19:31 +0000 en-US hourly 1 https://wordpress.org/?v=5.2 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png Angular 6 – AppDividend https://appdividend.com 32 32 Angular NgModel Directive Example Tutorial https://appdividend.com/2018/10/03/angular-ngmodel-directive-example-tutorial/ https://appdividend.com/2018/10/03/angular-ngmodel-directive-example-tutorial/#respond Wed, 03 Oct 2018 09:55:49 +0000 http://localhost/wordpress/?p=1821 Angular NgModel Tutorial

Angular NgModel Directive Example Tutorial is the today’s leading topic. The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.  Using the two-way binding, we can display a data property as well as an update that property when the user makes changes. We can merely achieve it in the component element as […]

The post Angular NgModel Directive Example Tutorial appeared first on AppDividend.

]]>
Angular NgModel Tutorial

Angular NgModel Directive Example Tutorial is the today’s leading topic. The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.  Using the two-way binding, we can display a data property as well as an update that property when the user makes changes. We can merely achieve it in the component element as well as HTML element both. The two-way binding uses the syntax as [()] or bind- keyword. The two-way binding uses the syntax of property binding and event binding together. Property binding uses the syntax as bracket [] or bind- and event binding uses the syntax as the parenthesis () or on- and these bindings are considered as one-way binding. Two-way binding works in both directions are setting the value and fetching the value. The two-way binding uses a specific name pattern.

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Join the program

Angular NgModel Directive Example Tutorial

Okay, let us install Angular using Angular CLI.

#1: Install Angular using AngularCLI

Type the following command to install Angular.

npm install -g @angular/cli

Now, generate the Angular project using the following command.

ng new model

 

Angular NgModel Directive Example Tutorial

Now, import the FormsModule inside the app.module.ts file.

// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

#2: Create the AppData model

Inside src >> app folder, create one file called AppData.ts and add the following code.

// AppData.ts

export class AppData {
  constructor(
      public name: String
  ) {}
}

So, here we have taken one property called name which is the type of String.

Now, import this model file inside the app.component.ts file.

// app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  data = new AppData('');
}

#3: Add HTML code

Okay, so to work two-way data binding correctly with ngModel, we need to write the following code inside the app.component.html file.

<input type="text" class="form-control" id="name" 
  required
  [(ngModel)]="data.name" />

<p>Hello {{ data.name }}!</p>
  • For each input tag, we use ngModel directive to bind data with syntax: [(ngModel)]="data.name" ( AppData is the data model in app.component.ts) class
  • Added a name attribute to the input tag. It is a requirement when using [(ngModel)] in combination with a form.

Save the file and go to the http://localhost:4200

You can see that using NgModel directive, and we can able to do the two-way data binding.

#Understanding NgModel

If we take a look at the source code, we’ll notice that ngModel comes with a property binding. The property binding [ngModel] takes care of updating the underlying input DOM element. Angular allows the shorthand syntax using [()], also called “Banana in a box”. So after all, it’s an implementation detail of ngModel that enables two-way data binding.

Finally, Angular NgModel Directive Example Tutorial is over.

The post Angular NgModel Directive Example Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2018/10/03/angular-ngmodel-directive-example-tutorial/feed/ 0
Angular Directive Example Tutorial https://appdividend.com/2018/09/17/angular-directive-example-tutorial/ https://appdividend.com/2018/09/17/angular-directive-example-tutorial/#respond Mon, 17 Sep 2018 12:03:21 +0000 http://localhost/wordpress/?p=1710

Angular Directive Example Tutorial is today’s leading topic.  Angular Directive is a class with a @Directive decorator. Decorators are the functions that modify JavaScript classes. The decorators are used for attaching metadata to classes as it knows the configuration of those classes and how they should work. You will be surprised to know that the component is also a directive-with-a-template. The @Component decorator is a @Directive decorator extended with template-oriented […]

The post Angular Directive Example Tutorial appeared first on AppDividend.

]]>

Angular Directive Example Tutorial is today’s leading topic.  Angular Directive is a class with a @Directive decorator. Decorators are the functions that modify JavaScript classes. The decorators are used for attaching metadata to classes as it knows the configuration of those classes and how they should work. You will be surprised to know that the component is also a directive-with-a-template. The @Component decorator is a @Directive decorator extended with template-oriented features.

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Join the program

Angular Directive Example Tutorial

An Angular Directive can be divided into two types: 

  1. Components
  2. Structural
  3. Attribute

#Structural Directives

Structural directives reconstruct the layout by adding, removing, and replacing elements in DOM. The structural directives are responsible for shape or reshape the DOM’s structure, typically by adding, deleting, or modifying elements. Similar to the other directives, you apply the structural directive to a host element. The directive then performs whatever it is intended to do with that host element. The structural directives are very simple to recognize. An asterisk (*) precedes the directive attribute name. It does not require brackets or parentheses like attribute directive.

Let us take an example. Generally, we loop through a data from the backend and display inside the table. It is the general case scenario in the web application. At that time, we use the *ngFor directive to loop through the data.

<table class="table table-hover">
  <thead>
  <tr>
      <td>Ad Unit Name</td>
      <td>Ad Unit Price</td>
      <td colspan="2">Actions</td>
  </tr>
  </thead>

  <tbody>
      <tr *ngFor="let adunit of adunits">
          <td>{{ adunit.unit_name }}</td>
          <td>{{ adunit.unit_price }}</td>
      </tr>
  </tbody>
</table>

So, in the above example, we have loop through the ad units and display the ad unit one by one. Three of the standard, built-in structural directives are NgIf, NgFor, and NgSwitch. The Directives can be written in both the UpperCamelCase and lowerCamelCase because NgIf refers to a directive class & ngIf refers to a directive’s attribute name.

#Attribute Directives

An Attribute directive changes the appearance or behavior of a Document Object Model(DOM) element. The attribute directives are used as attributes of elements. The built-in NgStyle directive in the Template Syntax guide, for example, can change several element styles at the same time.

You can generate the attribute directive using the following command.

ng g directive directive_name

Directives must be declared in Angular Modules in the same manner as components.

#Example

Install Angular using Angular CLI. First, create an angular project using the following command.

ng new directive

Now, go inside the folder.

cd directive

Generate Angular Directive using the following command.

ng g directive active

The generated src/app/active.directive.ts is as follows:

// active.directive.ts

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

@Directive({
  selector: '[appActive]'
})
export class ActiveDirective {

  constructor() { }

}

The imported Directive symbol provides the Angular the @Directive decorator.

The @Directive decorator’s lone configuration property specifies the directive’s CSS attribute selector [appActive].

It is the brackets ([]) that make it an attribute selector. Angular locate each element in the template that has an attribute named appActive and applies the logic of this directive to that element.

The attribute selector pattern explains the name of this kind of directive.

Now, define the behavior of the directive. So we need to add code inside the constructor of an ActiveDirective class.

// active.directive.ts

import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[appActive]'
})
export class ActiveDirective {

  constructor(el: ElementRef) {
    el.nativeElement.style.backgroundColor = 'Green';
  }

}

Now, we can use the directive inside our HTML component. Write the following code in an app.component.html file.

<!-- app.component.html -->

<p appActive>Active !!</p>

Save the file and start the development server.

ng serve --open

 

Angular Directive Example Tutorial

You can see that; we got the green background color of the text. Which is cool because we have first created the custom directive and add that directive to our HTML element.

Here, we have modified the DOM through the angular directive. We have changed the color of p element through angular attribute directive.

Finally, Angular Directive Example Tutorial is over. Thanks for taking.

The post Angular Directive Example Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2018/09/17/angular-directive-example-tutorial/feed/ 0
Angular Charts Example Tutorial https://appdividend.com/2018/09/12/angular-charts-example-tutorial/ https://appdividend.com/2018/09/12/angular-charts-example-tutorial/#comments Wed, 12 Sep 2018 21:14:20 +0000 http://localhost/wordpress/?p=1668 Angular Charts Tutorial From Scratch

Angular Charts Example Tutorial is today’s leading topic. We will use the chart.js library to construct the charts. I am using Angular 6 for this example. For that, you already have installed the Node.js in your machine because we use Angular CLI to install Angular. So node and npm is the must requirement for this example. So If you have not installed previously, then […]

The post Angular Charts Example Tutorial appeared first on AppDividend.

]]>
Angular Charts Tutorial From Scratch

Angular Charts Example Tutorial is today’s leading topic. We will use the chart.js library to construct the charts. I am using Angular 6 for this example. For that, you already have installed the Node.js in your machine because we use Angular CLI to install Angular. So node and npm is the must requirement for this example. So If you have not installed previously, then you can go to this link.

If you want to learn more about Angular 7 then check out this Angular 7 – The complete Guide course.

Angular Charts Example Tutorial

Okay, first install the Angular.

#1: Install Angular using Angular CLI

If you have not installed Angular CLI globally, then please install it using the following command.

sudo npm install -g @angular/cli

If you are Linux or Mac user then and then write sudo. In windows, open the CMD in admin mode and write the above command without sudo.

Now, create a new project using the following command.

ng new charts

 

Angular Charts Example Tutorial

Go into the project folder.

cd charts

Open the project inside Editor using the following command.

code .

Now, install the chartjs library using the following command.

npm install chart.js --save

Also, you need to install rxjs-compat package. Some third-party packages are incompatible with Angular 6 that is why we need to add the following package to bridge the gap.

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Join the program
npm install rxjs-compat.js --save

#2: Create a server that serves backend data.

We need the fake data to work with that is why I am using one package called json-server for this example. So let us install the package using Yarn package manager. If you have previously installed, then you do not need to install it again.

npm install -g json-server

Now, create one file called data.json inside the root of the project. We will see the chart of the Apple’s stock price from Jan to Sept.

{
  "results": [
  {
      "month": "Jan",
      "price": "180"
  },
  {
    "month": "Feb",
    "price": "200"
  },
  {
    "month": "March",
    "price": "210"
  },
  {
    "month": "April",
    "price": "190"
  },
  {
    "month": "May",
    "price": "240"
  },
  {
    "month": "June",
    "price": "230"
  },
  {
    "month": "July",
    "price": "260"
  },
  {
    "month": "Aug",
    "price": "210"
  },
  {
    "month": "Sept",
    "price": "300"
  }]
}

Now, start the JSON Server using the following command.

json-server --watch data.json --port 4000

 

Angular 6 Charts Tutorial Example

#3: Add HttpClientModule in app.module.ts file.

Write the following code inside an app.module.ts file.

// app.module.ts

import { HttpClientModule } from '@angular/common/http';

imports: [
    ...
    HttpClientModule
],

Okay, now we can use http module inside an app.component.ts file.

// app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  constructor(private httpClient: HttpClient) {}
}

#4: Create a data.ts file

Inside the src >> app folder, create one file called Data.ts and add the following code in it.

// Data.ts

export interface Data {
  month: String;
  price: Number;
}

So we are expecting month and price data from an API.

#5: Send a request and display chart.

Now, we need to import the Chart library inside an app.component.ts file and then use Chart api to display the data. The dataset for this example comes from the backend json server.

// app.component.ts

import { Component, OnInit } from '@angular/core';
import { Chart } from 'chart.js';
import { HttpClient } from '@angular/common/http';
import { Data } from './Data';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'app';
  data: Data[];
  url = 'http://localhost:4000/results';
  month = [];
  price = [];
  chart = [];
  constructor(private httpClient: HttpClient) {}

  ngOnInit() {
    this.httpClient.get(this.url).subscribe((res: Data[]) => {
      res.forEach(y => {
        this.month.push(y.month);
        this.price.push(y.price);
      });
      this.chart = new Chart('canvas', {
        type: 'line',
        data: {
          labels: this.month,
          datasets: [
            {
              data: this.price,
              borderColor: '#3cba9f',
              fill: false
            }
          ]
        },
        options: {
          legend: {
            display: false
          },
          scales: {
            xAxes: [{
              display: true
            }],
            yAxes: [{
              display: true
            }],
          }
        }
      });
    });
  }
}

So, here first we have sent the request to a server and we get the response. Now, we have stored the response in two different arrays because further in the chart, we need to use that arrays.

One array called a month is for the label and another is called price for the dataset.

We have constructed the line chart for this example, but you can create more. Follow the official docs.

#6: Add chart inside the app.component.html file.

The final step would be to add the chart inside the app.component.html file.

<div *ngIf="chart">
  <canvas id="canvas">{{ chart }}</canvas>
</div>

Save the file. Also, check your app.module.ts file with mine.

// app.module.ts

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

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Go to the terminal and type the following command to start the Angular development server.

ng serve --open

It will open the browser and you can see the Chart like below image.

 

Charts in Angular 6

Finally, Angular Charts Example Tutorial is over. Thanks for taking this demo.

The post Angular Charts Example Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2018/09/12/angular-charts-example-tutorial/feed/ 3
Angular Material Example Tutorial From Scratch https://appdividend.com/2018/09/07/angular-material-example-tutorial-from-scratch/ https://appdividend.com/2018/09/07/angular-material-example-tutorial-from-scratch/#comments Fri, 07 Sep 2018 18:42:22 +0000 http://localhost/wordpress/?p=1624 Angular 6 Material Example Tutorial For Beginners

Angular Material Example Tutorial From Scratch is today’s leading topic.  We use Angular 6 and Angular Material 6 for this demo.  Angular Material is ground running with large, modern UI components that work across the web, mobile, and desktop. Angular Material components will help us in constructing attractive UI and UX, consistent, and functional web pages and web applications while keeping to modern […]

The post Angular Material Example Tutorial From Scratch appeared first on AppDividend.

]]>
Angular 6 Material Example Tutorial For Beginners

Angular Material Example Tutorial From Scratch is today’s leading topic.  We use Angular 6 and Angular Material 6 for this demo.  Angular Material is ground running with large, modern UI components that work across the web, mobile, and desktop. Angular Material components will help us in constructing attractive UI and UX, consistent, and functional web pages and web applications while keeping to modern web design principles like browser portability and compatibility, device independence, and graceful degradation. Angular Material helps in creating faster, beautiful, and responsive web apps and websites. You can find more about Angular Material on their official docs.

If you want to learn more about Angular 7 then check out this Angular 7 – The complete Guide course.

Angular Material Example Tutorial

First, we need to install Angular. We are using Angular CLI to install the Angular. Right now, Angular 6 is the latest. So if you have not installed Angular CLI then install it using the following command.

#1: Install Angular CLI on Mac

Type the following command.

npm install -g @angular/cli

If you are using Mac, then prepend sudo, and if you are the windows user, then please open the CMD in Administrator mode, and you can install the above package globally on your machine.

Now, generate the Angular project using the following command.

ng new material

#2: Install other libraries.

Go into the project and install the hammerjs using the following command.

npm install --save hammerjs

Hammer.js is the optional dependency and helps with touch support for a few of the components.

Now, install Angular Material and Angular Animations using the following command.

npm install --save @angular/material @angular/animations @angular/cdk

Now, include hammerjs inside the angular.json file. You can find this file on the root of the project.

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Join the program
"scripts": [
     "./node_modules/hammerjs/hammer.min.js"
]

#3: Create a Custom Material Module File.

Okay, now inside src >> app folder, create one module file called material.module.ts.

Write the following code inside the material.module.ts file.

// material.module.ts

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

import {
  MatButtonModule,
  MatCardModule
} from '@angular/material';

@NgModule({
  imports: [
    MatButtonModule,
    MatCardModule
  ],
  exports: [
    MatButtonModule,
    MatCardModule
  ]
})

export class MaterialModule {}

Here, we have imported all the components that we need in our Material Angular App. We can add other components in future if we need. The reason this file is written on its own is that it is easy to include all the Material components in this file and later this file will be imported inside the app.module.ts.

#4: Import a pre-built theme and Material icons

Angular Material comes with some pre-built themes. These themes have set off the colors and basic styling. The main available themes are indigo-pinkdeeppurple-amberpurple-green and pink-bluegrey.

To import the theme, you can add the following code to your global styles.css file. The file is inside src folder.

@import '~@angular/material/prebuilt-themes/indigo-pink.css';

You can also have access to the Material Design icons and use named icons with the <mat-icon> component. To import them to your project, you can add this to the head section of your project’s root index.html file.

  <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

Now the final step is to import material.module.ts and other angular material module files inside the app.module.ts file.

// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { MaterialModule } from './material.module';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    MaterialModule,
    BrowserAnimationsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Also, write the html inside an app.component.html file.

<div>
  <mat-card>
    <button mat-raised-button>Cersie Lannister</button>
    <button mat-raised-button color="primary">Jaime Lannister</button>
    <button mat-raised-button color="accent">Tyrion Lannister</button>
  </mat-card>
</div>

Now start the Angular development server using the following command.

ng serve --open

 

Angular Material Example Tutorial

Finally, we have completed the steps to include Material in Angular Framework.

#5: Different Angular Components.

Let us add a text input inside our application. First, import the material component inside the material.module.ts file.

//material.module.ts

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

import {
  MatButtonModule,
  MatCardModule,
  MatInputModule
} from '@angular/material';

@NgModule({
  
  exports: [
    MatButtonModule,
    MatCardModule,
    MatInputModule
  ]
})

export class MaterialModule {}

Now, write the HTML for that inside app.component.html file.

<div>
  <mat-card>
    <button mat-raised-button>Cersie Lannister</button>
    <button mat-raised-button color="primary">Jaime Lannister</button>
    <button mat-raised-button color="accent">Tyrion Lannister</button>
  </mat-card>
  <form class="form-center">
    <mat-form-field class="example-full-width">
      <input matInput placeholder="Favorite food" value="Pizza">
    </mat-form-field>
  </form>
</div>

Also, if you need to give some designing to the app component, then you need to write that css code in the component-specific css file, and in our case it is app.component.css.

.form-center {
  margin-top: 20px
}

Save the file and go to the browser and you can see the textbox is there.

#Navigation in Angular Material

For navigation, basically, we need the following angular material modules.

  1. MatMenuModule
        2. MatToolbarModule

 

We can also import the Angular Material Icons for that. Let us do it inside the material.module.ts file.

// material.module.ts

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

import {
  MatButtonModule,
  MatCardModule,
  MatInputModule,
  MatMenuModule,
  MatIconModule,
  MatToolbarModule,
} from '@angular/material';

@NgModule({

  exports: [
    MatButtonModule,
    MatCardModule,
    MatInputModule,
    MatMenuModule,
    MatIconModule,
    MatToolbarModule
  ]
})

export class MaterialModule {}

Also, write the HTML code inside an app.component.html file.

<div>
  <mat-toolbar color="primary">
    <span>Angular Material Tutorial</span>
    <button mat-icon-button [mat-menu-trigger-for]="menu">
      <mat-icon>more_vert</mat-icon>
    </button>
  </mat-toolbar>
  <mat-menu x-position="before" #menu="matMenu">
    <button mat-menu-item>About</button>
    <button mat-menu-item>Contact</button>
  </mat-menu>
  <mat-card>
    <button mat-raised-button>Cersie Lannister</button>
    <button mat-raised-button color="primary">Jaime Lannister</button>
    <button mat-raised-button color="accent">Tyrion Lannister</button>
  </mat-card>
  <form class="form-center">
    <mat-form-field class="example-full-width">
      <input matInput placeholder="Favorite food" value="Pizza">
    </mat-form-field>
  </form>
</div>

Save the file and the output looks like below.

 

Angular 6 Material Example Tutorial For Beginners

Finally, Angular Material Example Tutorial From Scratch is over. Thanks for taking.

The post Angular Material Example Tutorial From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2018/09/07/angular-material-example-tutorial-from-scratch/feed/ 5
Angular NGXS Tutorial With Example From Scratch https://appdividend.com/2018/07/03/angular-ngxs-tutorial-with-example-from-scratch/ https://appdividend.com/2018/07/03/angular-ngxs-tutorial-with-example-from-scratch/#comments Tue, 03 Jul 2018 12:17:55 +0000 http://localhost/wordpress/?p=1249 Angular NGXS Example Tutorial

Angular NGXS Tutorial With Example From Scratch is the today’s leading topic. We have covered the Angular NgRx Store pattern in this blog, and now it is time for an alternative to this library called Angular NGXS. Ngxs is a different approach to Angular state management. The official documentation for NGXS library is here. If you want to […]

The post Angular NGXS Tutorial With Example From Scratch appeared first on AppDividend.

]]>
Angular NGXS Example Tutorial

Angular NGXS Tutorial With Example From Scratch is the today’s leading topic. We have covered the Angular NgRx Store pattern in this blog, and now it is time for an alternative to this library called Angular NGXS. Ngxs is a different approach to Angular state management. The official documentation for NGXS library is here.

If you want to learn more about Angular 7 then check out this Angular 7 – The complete Guide course.

#What is NGXS

NGXS is a state management pattern for the Angular framework. NGXS acts as a single source of truth for your application’s state, providing simple rules for predictable state mutations. The concept is same as a Redux library mostly used in React application. You can not directly change the state; you need to commit the action and then modify the state. NGXS is modeled after the CQRS pattern popularly implemented in libraries like Redux and NGRX but reduces boilerplate by using modern TypeScript features such as classes and decorators.

#Flow of NGXS

The flow of NGXS is effortless.

  1. Angular component dispatches the action.
  2. If the action needs to change the database values, then it sends a network request to the server and performs the database operations.
  3. Then after getting a response from the server, it will mutate the state. If the backend is not there, then action directly mutate the state of the store and component select that state and update the UI. It is the same cycle as Redux if you are familiar with it. You can find more on here.

Angular NGXS Tutorial With Example

We start this demo example by installing the Angular 6 using Angular CLI.

#Step 1: Install Angular.

If you have not previously installed Angular CLI globally on your machine, then install it using the following command.

npm install -g @angular/cli

# or

yarn add global @angular/cli

Create an Angular 6 project using the following command.

ng new ng6xs

 

Angular NGXS Tutorial With Example

Step 2: Install NGXS Store.

Next, we’ll install ngxs store.

yarn add @ngxs/store

 

Angular NGXS Store

Now install logger-plugin and devtools-plugin as a development dependency.

yarn add @ngxs/logger-plugin @ngxs/devtools-plugin --dev

Now, import these modules inside an app.module.ts file.

// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { NgxsModule } from '@ngxs/store';
import { NgxsReduxDevtoolsPluginModule } from '@ngxs/devtools-plugin';
import { NgxsLoggerPluginModule } from '@ngxs/logger-plugin';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    NgxsModule.forRoot(),
    NgxsReduxDevtoolsPluginModule.forRoot(),
    NgxsLoggerPluginModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Type the following command to start the Angular Development server.

ng serve -o

 

NGXS Example in Angular

You can see the logs, so when the state changes, we can its old and new values.

Step 3: Create components.

Inside src >> app folder, create one folder called components.

Now, we will create and display the user information like name and email. We do not make a backend to store the user information. We need to add the data to the store and display data on the Angular Frontend.

We will create two components, so type the following command to generate the Angular components.

ng g c components/create --spec=false
ng g c components/index --spec=false

 

Angular NGXS Example

Also,  install the  Bootstrap 4 using the following command.

yarn add bootstrap

Now, add the following code inside src >> styles.css file.

@import "~bootstrap/dist/css/bootstrap.min.css"

Inside src >> app >> components >> create folder, we need to add some HTML code inside create.component.html file.

<div class="card">
  <div class="card-body">
    <form>
      <div class="form-group">
        <label class="col-md-4">Name</label>
        <input type="text" class="form-control" #name/>
      </div>
      <div class="form-group">
        <label class="col-md-4">Email</label>
        <input type="email" class="form-control" #email/>
        </div>
        <div class="form-group">
          <button (click)="addUser(name.value, email.value)" class="btn btn-primary">Create User</button>
        </div>
    </form>
  </div>
</div>

Now, add this component inside an app.component.html file.

<div class="container">
  <div class="row">
    <div class="col-md-6">
      <app-create></app-create>
    </div>
    <div class="col-md-6"></div>
  </div>
</div>

Save the file and go to the: http://localhost:4200/. You can see something like below.

NGXS State Management Library

 

Okay, now we need the ReactiveFormsModule. We will use the Reactive approach to the form and not template-driven approach. So Inside app.module.ts file, add the ReactiveFormsModule from @angular/forms package.

// app.module.ts

import { ReactiveFormsModule } from '@angular/forms';

 imports: [
    BrowserModule,
    NgxsModule.forRoot(),
    NgxsReduxDevtoolsPluginModule.forRoot(),
    NgxsLoggerPluginModule.forRoot(),
    ReactiveFormsModule
  ],

Now, write the following code inside a create.component.ts file.

// create.component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'app-create',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css']
})
export class CreateComponent implements OnInit {

  angForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.createForm();
  }

  createForm() {
    this.angForm = this.fb.group({
      name: ['', Validators.required ],
      email: ['', Validators.required ]
   });
  }

  addUser(name, email) {
    console.log(name, email);
  }

  ngOnInit() {
  }

}

And finally, write the html code inside a create.component.html file.

<div class="card">
  <div class="card-body">
    <form [formGroup]="angForm">
      <div class="form-group">
        <label class="col-md-4">Name</label>
        <input type="text" class="form-control" formControlName="name" #name/>
        <div *ngIf="angForm.controls['name'].invalid && (angForm.controls['name'].dirty || angForm.controls['name'].touched)" class="alert alert-danger">
          <div *ngIf="angForm.controls['name'].errors.required">
            Name is required.
          </div>
        </div>
      </div>
      <div class="form-group">
        <label class="col-md-4">Email</label>
        <input type="email" class="form-control" formControlName="email" #email/>
        <div *ngIf="angForm.controls['email'].invalid && (angForm.controls['email'].dirty || angForm.controls['email'].touched)" class="alert alert-danger">
          <div *ngIf="angForm.controls['email'].errors.required">
            Email is required.
          </div>
        </div>
      </div>
      <div class="form-group">
        <button (click)="addUser(name.value, email.value)" 
            class="btn btn-primary"
            [disabled]="angForm.pristine || angForm.invalid">Create User</button>
      </div>
    </form>
  </div>
</div>

#Step 4: Define model.

Inside src >> app folder, create one folder called models and inside that create one file called User.ts.

// User.ts

export interface User {
    name: string;
    email: string;
}

#Step 5: Define Actions.

We will create the addUser action. Inside src >> app folder, create one folder called actions. Inside actions folder, create one file called user.action.ts.

// user.action.ts

import { User } from '../models/User';

export class AddUser {
    static readonly type = '[User] Add';

    constructor(public payload: User) {}
}

#Step 6: Defining a State.

A key difference between Ngrx and Ngxs is how the state is handled. The state file in Ngxs takes the place of reducers in Ngrx. This is done by utilizing various decorators.

Inside src >> app folder, create one folder called state and in that folder, create one file called user.state.ts.

Write the following code inside the user.state.ts file.

// user.action.ts

import { State, Action, StateContext, Selector } from '@ngxs/store';
import { User } from '../models/User';
import { AddUser } from '../actions/user.action';

export class UserStateModel {
    users: User[];
}

@State<UserStateModel>({
    name: 'users',
    defaults: {
        users: []
    }
})
export class UserState {

    @Selector()
    static getUsers(state: UserStateModel) {
        return state.users;
    }

    @Action(AddUser)
    add({getState, patchState }: StateContext<UserStateModel>, { payload }: AddUser) {
        const state = getState();
        patchState({
            users: [...state.users, payload]
        });
    }
}

Here, we have defined the action to save the user data into the store. When the user tries to create the new user, we get those payload values here and add into the user’s state array. So, when the user is created, the store will update its user state and that state is fetched by another component. In our case it is index.component.ts. So it will change its UI and display the newly created user.

Finally, import the store inside a create.component.ts file.

// create.component.ts

import { Component, OnInit } from '@angular/core';
import { Store } from '@ngxs/store';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

import { AddUser } from '../../actions/user.action';

@Component({
  selector: 'app-create',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css']
})
export class CreateComponent implements OnInit {

  angForm: FormGroup;

  constructor(private fb: FormBuilder, private store: Store) {
    this.createForm();
  }

  createForm() {
    this.angForm = this.fb.group({
      name: ['', Validators.required ],
      email: ['', Validators.required ]
   });
  }

  addUser(name, email) {
    this.store.dispatch(new AddUser({ name, email}));
  }

  ngOnInit() {
  }

}

#Step 7: Updating the app.module.ts file.

// user.state.ts

import { UserState } from './state/user.state';

imports: [
    BrowserModule,
    NgxsModule.forRoot([
      UserState
    ]),
    NgxsReduxDevtoolsPluginModule.forRoot(),
    NgxsLoggerPluginModule.forRoot(),
    ReactiveFormsModule
  ],

#Step 8: Display the data.

Write the following code inside the index.component.ts file.

// index.component.ts

import { Component, OnInit } from '@angular/core';
import { Store, Select } from '@ngxs/store';
import { User } from '../../models/User';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-index',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.css']
})
export class IndexComponent implements OnInit {

  users: Observable<User>;

  constructor(private store: Store) {
    this.users = this.store.select(state => state.users.users);
   }

  ngOnInit() {
  }

}

Here, if the user’s state array is changed then this component rerenders and display the changes. For example, if the new user is added then this component rerenders and display the new user. 

Also, write the HTML code inside an index.component.html file.

<div *ngIf="users">
  <table class="table table-striped">
    <thead>
      <tr>
        <th>Name</th>
        <th>Email</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let user of users | async">
        <td>{{ user.name }}</td>
        <td>{{ user.email }}</td>
      </tr>
    </tbody>
  </table>
</div>

Now, include this component inside an app.component.html file.

<div class="container">
  <div class="row">
    <div class="col-md-6">
      <app-create></app-create>
    </div>
    <div class="col-md-6">
      <app-index></app-index>
    </div>
  </div>
</div>

Save the file and go to the browser. You can see below.

Angular State Management Pattern

Finally, Angular NGXS Tutorial With Example is over. Thanks for taking.

Github Code

The post Angular NGXS Tutorial With Example From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2018/07/03/angular-ngxs-tutorial-with-example-from-scratch/feed/ 4
Angular 6 File Upload Tutorial https://appdividend.com/2018/05/25/angular-6-file-upload-tutorial/ https://appdividend.com/2018/05/25/angular-6-file-upload-tutorial/#comments Fri, 25 May 2018 10:12:23 +0000 http://localhost/wordpress/?p=896 Angular File Upload Example

Angular 6 File Upload Tutorial. In this example, We will use an ng2-file-upload library to upload a file to the server. We use Node.js as a backend server. We install Angular 6 using Angular CLI and then start working on this Angular File Upload demo. For managing the uploaded files at the backend, we use […]

The post Angular 6 File Upload Tutorial appeared first on AppDividend.

]]>
Angular File Upload Example

Angular 6 File Upload Tutorial. In this example, We will use an ng2-file-upload library to upload a file to the server. We use Node.js as a backend server. We install Angular 6 using Angular CLI and then start working on this Angular File Upload demo. For managing the uploaded files at the backend, we use the multer library.

If you want to learn more about Angular 7 then check out this Angular 7 – The complete Guide course.

Angular 6 File Upload Tutorial

We start this project by installing Angular on our machine.

Step 1: Install Angular 6.

If you have not installed Angular CLI globally on your machine, then install it using the following command.

npm install -g @angular/cli

# or

yarn add global @angular/cli

Now, create a local project using the following command.

ng new fileupload

Now, start the application using the following command.

ng serve --open

Step 2: Install rxjs-compat library.

Since third-party libraries do not support the RxJS 6. Now, one change in Angular 6 is that Angular 6 now depends on TypeScript 2.7 and RxJS 6. So, if you install third-party packages right now, then it is not compatible with Angular 6. In future, all the third-party libraries might upgrade their packages, but right now, it is not compatible with Angular 6.

So, to fill the gap between Angular 6 and third-party packages, we need to install the following library. That is it.

npm install rxjs-compat --save

Step 4: Install Bootstrap 4.

Go to your terminal and type the following command.

npm install bootstrap --save

After that go to the inside src folder and open styles.css file and import the bootstrap.min.css file.

@import "~bootstrap/dist/css/bootstrap.min.css"

Step 5: Install ng-file-upload library.

Type the following command to install the library.

npm install ng2-file-upload --save

Now, write the following code inside an app.module.ts file.

// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FileSelectDirective } from 'ng2-file-upload';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
    FileSelectDirective
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Okay, so we have imported FormsModule and FileSelectDirective.

Now, write the following code inside an app.component.ts file.

// app.component.ts

import { Component, OnInit } from '@angular/core';
import {  FileUploader, FileSelectDirective } from 'ng2-file-upload/ng2-file-upload';

const URL = 'http://localhost:3000/api/upload';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'app';

  public uploader: FileUploader = new FileUploader({url: URL, itemAlias: 'photo'});

  ngOnInit() {
    this.uploader.onAfterAddingFile = (file) => { file.withCredentials = false; };
    this.uploader.onCompleteItem = (item: any, response: any, status: any, headers: any) => {
         console.log('ImageUpload:uploaded:', item, status, response);
         alert('File uploaded successfully');
     };
 }
}

Finally, write the following code inside an app.component.html file.

<input type="file" name="photo" ng2FileSelect [uploader]="uploader" />

<button type="button" class="btn btn-success btn-s" 
  (click)="uploader.uploadAll()" 
  [disabled]="!uploader.getNotUploadedItems().length" >
      Upload an Image
</button>

 

Angular 6 File Upload Tutorial

Step 6: Create Node.js backend.

First, install the following node modules.

npm install express multer body-parser --save

Install nodemon as a dev dependency.

npm install nodemon --save-dev

Create a new directory inside root called uploads.

Okay, now create one file in the project root folder called server.js.

// server.js

const path = require('path');
const fs = require('fs');
const express = require('express');
const multer = require('multer');
const bodyParser = require('body-parser')
const app = express();
const router = express.Router();

const DIR = './uploads';
 
let storage = multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, DIR);
    },
    filename: (req, file, cb) => {
      cb(null, file.fieldname + '-' + Date.now() + '.' + path.extname(file.originalname));
    }
});
let upload = multer({storage: storage});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
 
app.use(function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
  res.setHeader('Access-Control-Allow-Methods', 'POST');
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
  res.setHeader('Access-Control-Allow-Credentials', true);
  next();
});
 
app.get('/api', function (req, res) {
  res.end('file catcher example');
});
 
app.post('/api/upload',upload.single('photo'), function (req, res) {
    if (!req.file) {
        console.log("No file received");
        return res.send({
          success: false
        });
    
      } else {
        console.log('file received');
        return res.send({
          success: true
        })
      }
});
 
const PORT = process.env.PORT || 3000;
 
app.listen(PORT, function () {
  console.log('Node.js server is running on port ' + PORT);
});

So, I have used multer module to store the file.

Now, start the server using the following command.

nodemon server

Step 7: Run the project.

Start both the server, if not started.

  1. ng server –open
  2. nodemon server

Go to the http://localhost:4200/

Now, until you have not selected any file, the upload an image button will remain disabled.

Upload an image, and see the response you get in the browser console.

Angular Node.js Image Upload

 

Finally, Angular 6 File Upload Tutorial is over. Thanks for taking.

The post Angular 6 File Upload Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2018/05/25/angular-6-file-upload-tutorial/feed/ 37
Angular 6 Smart Table Example https://appdividend.com/2018/05/13/angular-6-smart-table-example/ https://appdividend.com/2018/05/13/angular-6-smart-table-example/#comments Sun, 13 May 2018 08:43:33 +0000 http://localhost/wordpress/?p=735 Angular 6 Datatable Example

In this tutorial, we will see Angular 6 Smart Table Example.  We use the ng2-smart-table library for this example. The ng2-smart-table library provides us sorting, searching and filtering functionalities. So let us start this example. If you want to learn more about Angular 7 then check out this Angular 7 – The complete Guide course. Angular 6 Smart Table Example. First, we start our tutorial by installing Angular […]

The post Angular 6 Smart Table Example appeared first on AppDividend.

]]>
Angular 6 Datatable Example

In this tutorial, we will see Angular 6 Smart Table Example.  We use the ng2-smart-table library for this example. The ng2-smart-table library provides us sorting, searching and filtering functionalities. So let us start this example.

If you want to learn more about Angular 7 then check out this Angular 7 – The complete Guide course.

Angular 6 Smart Table Example.

First, we start our tutorial by installing Angular 6 CLI. If you have already installed, then you can skip the installation.

Step 1: Install Angular 6 project.

npm install -g @angular/cli

If it does not install then try in the administrator mode.

Now, after that, create a new Angular 6 application using the following command.

ng new ngtable

Go into the project directory.

cd ngtable

Start the server by typing the following command.

ng serve --open

Now, one change in Angular 6 is that Angular 6 now depends on TypeScript 2.7 and RxJS 6. So, if you install third-party packages right now, then it is not compatible with Angular 6. In future, all the third-party libraries might upgrade their packages, but right now, it is not compatible with Angular 6.

So, to fill the gap between Angular 6 and third-party packages, we need to install the following library. That is it.

npm i rxjs-compat --save

Step 2: Install the ng2-smart-table library.

Install it via the following command.

npm install --save ng2-smart-table

Inside app.module.ts file, write the following code to register this module inside our Angular application.

// app.module.ts

import { Ng2SmartTableModule } from 'ng2-smart-table';

@NgModule({
  imports: [
    // ...
    
    Ng2SmartTableModule,
    
    // ...
  ],
  declarations: [ ... ]
})
// ...

Step 3: Create a Table Component.

Type the following command to generate the component.

ng g c table

Now, import this component inside app.component.ts file.

// app.component.ts

import { Component } from '@angular/core';
import { TableComponent } from './table/table.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
}

Write only the following code inside an app.component.html file.

<app-table></app-table>

Save the file and see this URL: http://localhost:4200/ You can see in the page: table works!

Step 4: Create a backend server.

We need the fake data to work with that is why I am using one package called json-server for this tutorial. Okay, so let us install the package using Yarn package manager.

yarn global add json-server

# or

npm install -g json-server

Now we need to create a folder inside src directory called data and in that folder, create one file called db.json. Let us add the following data inside a db.json file.

{
    "characters": [
    {
        "id": "1",
        "name": "Peter Dinklage",
        "age": "45"
    },
    {
        "id": "2",
        "name": "Lina Heady",
        "age": "43"
    },
    {
        "id": "3",
        "name": "Emilia Clarke",
        "age": "30"
    },
    {
        "id": "4",
        "name": "Kit Harrington",
        "age": "30"
    },
    {
        "id": "5",
        "name": "Sean Bean",
        "age": "50"
    }]
}

Now, start the JSON server using the following command.

json-server --watch src/data/db.json --port 4000

Now, we have a server running that can feed the data to our React Bootstrap Application.

Our JSON server is started at port: 4000 and URL is: http://localhost:4000/characters

Step 5: Setup HttpClient.

Angular is full fledge Frontend Framework, so it has already HTTP module. So first let us configure inside app.module.ts file.

// app.module.ts

import { HttpClientModule } from '@angular/common/http';

imports: [
    BrowserModule,
    Ng2SmartTableModule,
    HttpClientModule
 ],

Now, inside table folder, create one file called Table.ts. It is an interface, which tells the Angular application that, which kind of data is on the backend that we need to display at frontend.

// Table.ts

export interface Table {
    id: Number;
    name: String;
    age: Number;
}

Also, inside table folder, create one file called table.service.ts. We are writing the network request code inside this file. Then we import this file inside table.component.ts file and then call service file’s function.

// table.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class TableService {
  constructor(private http: HttpClient) { }
  url = 'http://localhost:4000';
  getCharacters() {
    return this
            .http
            .get(`${this.url}/characters`);
        }
}

Also, we need to import this service file inside app.module.ts.

// app.module.ts

import { TableService } from './table/table.service';

providers: [TableService],

Finally, we need to call the service function from table.component.ts file.

// table.component.ts

import { Component, OnInit } from '@angular/core';
import { TableService } from './table.service';
import { Table } from './Table';

@Component({
  selector: 'app-table',
  templateUrl: './table.component.html',
  styles: []
})
export class TableComponent implements OnInit {

  characters: Table[];

  constructor(private tservice: TableService) { }

  ngOnInit() {
    this
      .tservice
      .getCharacters()
      .subscribe((data: Table[]) => {
        this.characters = data;
    });
  }

}

Now, finally, write the template code inside a table.component.html file.

<table>
    <thead>
      <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Age</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let character of characters">
        <td>{{ character.id }}</td>
        <td>{{ character.name }}</td>
        <td>{{ character.age }}</td>
      </tr>
    </tbody>
</table>

It will output like below image.

Angular 6 Smart Table Example

 

Step 6: Configure the Angular Smart Table.

Now, create the settings object inside table.component.ts file.

This object contains columns that need to be displayed on the table.

// table.component.ts

settings = {
    columns: {
      id: {
        title: 'ID'
      },
      name: {
        title: 'Name'
      },
      age: {
        title: 'Age'
      }
    }
  };

The columns keys contain the column name and title is the table’s column title. Both are different things. We right now only concern about column’s keys and that is id, name, and age. It is same as, the Table.ts properties.

Now, the second property we need to define is a source and the at is our actual data.

Also, now we can write the table.component.html file like this because we are now using the smart table. So we do not need to iterate the loop to display the data.

We can directly use the Directive provided by ng-smart-table and that is <ng-smart-table>

But that component needs two properties.

  1. settings
  2. source

The settings are our columns and source is our data and it is characters.

Now, write the following code inside the table.component.html and remove everything else.

// table.component.html

<ng2-smart-table 
    [settings]="settings" 
    [source]="characters">
</ng2-smart-table>

Save the file and see the browser: http://localhost:4200/

Angular Table Example with Pagination, Sorting and Searching

 

In that table, now you can searching and sorting based on columns.

There are lots of advanced things we can do on this table, but we will see in the upcoming tutorials.

Angular 6 Smart Table Example is over here. Thanks for taking.

The post Angular 6 Smart Table Example appeared first on AppDividend.

]]>
https://appdividend.com/2018/05/13/angular-6-smart-table-example/feed/ 12
Angular Routing Progress Indicator Tutorial https://appdividend.com/2018/05/12/angular-routing-progress-indicator-tutorial/ https://appdividend.com/2018/05/12/angular-routing-progress-indicator-tutorial/#comments Sat, 12 May 2018 08:36:23 +0000 http://localhost/wordpress/?p=727 Angular 6 Routing Indicator Progressbar Tutorial Example

Angular Routing Progress Indicator Tutorial is today’s main topic. Proper tools make application development quicker and easier to maintain if you did everything by hand. The Angular CLI is a command line interface tool that can create a project, add files, and perform a variety of ongoing development tasks such as testing, bundling, and deployment. In this example, I have used Angular […]

The post Angular Routing Progress Indicator Tutorial appeared first on AppDividend.

]]>
Angular 6 Routing Indicator Progressbar Tutorial Example

Angular Routing Progress Indicator Tutorial is today’s main topic. Proper tools make application development quicker and easier to maintain if you did everything by hand. The Angular CLI is a command line interface tool that can create a project, add files, and perform a variety of ongoing development tasks such as testing, bundling, and deployment. In this example, I have used Angular 6 because it is in the stable version now. So let us start our Angular Routing Progress Indicator Tutorial. You can find more about ng2-slim-loading-bar on its Github Library.

If you want to learn more about Angular 7 then check out this Angular 7 – The complete Guide course.

Final Output

 

Angular Routing Progress Indicator Tutorial

As always, we start our tutorial by installing the Angular 6.

Step 1. Set up the Development Environment

Install the Angular CLI globally, if you have not installed in previously.

npm install -g @angular/cli

If it does not install then try in administrator mode.

Now, after that, create a new application using the following command.

ng new ngindicator

Go into the project directory.

cd ngindicator

Now, open the project in your favorite editor. I am using VSCode.

code .

To start the development server, type the following command.

ng serve --open

Step 2: Install ng2-slim-loading-bar library.

Our goal of this tutorial is that, when we navigate to different routing components, we see the loading indicator. So for that, we need to install an ng2-slim-loading-bar library. So install using the following cmd.

npm install ng2-slim-loading-bar --save

Now, one of the significant change in Angular 6 is that Angular 6 now depends on TypeScript 2.7 and RxJS 6. So, if you install third-party packages right now, then it is not compatible with Angular 6.

To bridge the gap between Angular 6 and third-party packages, we need to install the following library. That is it.

npm i rxjs-compat --save

Now, import the SlimLoadingBarModule inside the app.module.ts file.

// app.module.ts

import { SlimLoadingBarModule } from 'ng2-slim-loading-bar';

imports: [
    BrowserModule,
    SlimLoadingBarModule
],

Next step is, include the styling that comes with the library inside src  >>  styles.css file.

// styles.css

@import "../node_modules/ng2-slim-loading-bar/style.css";

Step 3: Create three components.

Go to the terminal and create three components using the following commands.

ng g c mobile -it -is --spec false
ng g c tv -it -is --spec false
ng g c ac -it -is --spec false

Now, we do not need the test files for this example. Also, it automatically includes the component dependencies inside app.module.ts file. So we do not need to update it manually.

Now, configure the routes for these three components. Inside app.module.ts file, write the following code.

// app.module.ts

import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  {
    path: 'mobile',
    component: MobileComponent
  },
  {
    path: 'tv',
    component: TvComponent
  },
  {
    path: 'ac',
    component: AcComponent
  }
];

imports: [
    BrowserModule,
    SlimLoadingBarModule,
    RouterModule.forRoot(routes)
  ],

We have already included three components inside app.module.ts file and now create an array that contains these three components and then register the routes in our Angular 6 application. So our whole app.module.ts file looks like below.

// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { SlimLoadingBarModule } from 'ng2-slim-loading-bar';

import { AppComponent } from './app.component';
import { MobileComponent } from './mobile/mobile.component';
import { TvComponent } from './tv/tv.component';
import { AcComponent } from './ac/ac.component';

const routes: Routes = [
  {
    path: 'mobile',
    component: MobileComponent
  },
  {
    path: 'tv',
    component: TvComponent
  },
  {
    path: 'ac',
    component: AcComponent
  }
];

@NgModule({
  declarations: [
    AppComponent,
    MobileComponent,
    TvComponent,
    AcComponent
  ],
  imports: [
    BrowserModule,
    SlimLoadingBarModule,
    RouterModule.forRoot(routes)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now, write the following code inside an app.component.html file.

Step 4: Add Bootstrap 4 to our Angular application.

Go to your project root and install bootstrap 4 using the following command.

npm install bootstrap@4.0.0 --save

Now, copy the bootstrap.min.css file from node_modules/bootstrap/dist/css directory and paste inside src >>  assets folder. 

In the src >>  index.html file, add the bootstrap css file.

<link rel="stylesheet" href="assets/bootstrap.min.css">

Step 5: Add Navigation to our application.

Inside the app.component.html file, we need to add the bootstrap 4 classes.

<ng2-slim-loading-bar color="blue"></ng2-slim-loading-bar>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
          <a routerLink="mobile" class="nav-link">Mobile</a>
      </li>
      <li class="nav-item active">
          <a routerLink="tv" class="nav-link">TV</a>
      </li>
      <li class="nav-item active">
          <a routerLink="ac" class="nav-link">AC</a>
      </li>
    </ul>
  </div>  
</nav> <br />
<div class="container">
    <router-outlet></router-outlet>
</div>

Step 6: Adding Router Events.

Angular RouterModule gives us the following event modules.

  • NavigationStart
  • NavigationEnd
  • NavigationError
  • NavigationCancel
  • Router
  • Event

Now, write the following code inside app.component.ts file.

// app.component.ts

import { Component } from '@angular/core';
import {SlimLoadingBarService} from 'ng2-slim-loading-bar';
import { NavigationCancel,
        Event,
        NavigationEnd,
        NavigationError,
        NavigationStart,
        Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';

  constructor(private _loadingBar: SlimLoadingBarService, private _router: Router) {
    this._router.events.subscribe((event: Event) => {
      this.navigationInterceptor(event);
    });
  }
  private navigationInterceptor(event: Event): void {
    if (event instanceof NavigationStart) {
      this._loadingBar.start();
    }
    if (event instanceof NavigationEnd) {
      this._loadingBar.complete();
    }
    if (event instanceof NavigationCancel) {
      this._loadingBar.stop();
    }
    if (event instanceof NavigationError) {
      this._loadingBar.stop();
    }
  }
}

So, what the above writing code’s meaning is that when the NavigationStart event occurs then loadingBar object calls its start() method and we can see the loading indicator. Now, when the NavigationEnd then loadingBar call its complete() method.

If NavigationCancel or NavigationError event occurs then loadingBar’s stop() function will run. So simple logic behind show the navigation progress bar.

Angular Routing Progress Indicator Tutorial

 

Above image is simple interface we have built in this example. If you are navigating to other nav items then you can see the routing indicator. So Angular Routing Progress Indicator Tutorial is over here. I am putting this code on Github, so please checkout as well.

Fork Me On Github

The post Angular Routing Progress Indicator Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2018/05/12/angular-routing-progress-indicator-tutorial/feed/ 2
Angular 6 Tutorial With Example using Angular CLI https://appdividend.com/2018/05/05/angular-6-tutorial-with-example-using-angular-cli/ https://appdividend.com/2018/05/05/angular-6-tutorial-with-example-using-angular-cli/#comments Sat, 05 May 2018 00:26:54 +0000 http://localhost/wordpress/?p=648 Angular 6 Tutorial With Routing and HTTP example

Angular 6 Tutorial With Example using Angular CLI is the topic, we discuss today. Angular is One framework for Mobile & desktop. Angular puts you in control over scalability. Meet substantial data requirements by building data models on RxJS, Immutable.js or another push-model. We start this tutorial by installing Angular using Angular CLI and then working on our tutorial. If […]

The post Angular 6 Tutorial With Example using Angular CLI appeared first on AppDividend.

]]>
Angular 6 Tutorial With Routing and HTTP example

Angular 6 Tutorial With Example using Angular CLI is the topic, we discuss today. Angular is One framework for Mobile & desktop. Angular puts you in control over scalability. Meet substantial data requirements by building data models on RxJS, Immutable.js or another push-model. We start this tutorial by installing Angular using Angular CLI and then working on our tutorial.

If you want to learn advance about Angular and Node.js then check out below course. This course has a brief introduction about Angular and Node.js and how they can work together. It is a complete practical example of Angular and Node.js. I also found it very useful. The Complete Angular, React & Node Guide Airbnb Style App

Angular 6 Tutorial

First, we need to set up a development environment.

Step 1: Set up the Development Environment.

Install Node.js® and npm if they are not already on your machine.

Then install the Angular CLI globally.

# run in administrator mode

sudo npm install -g @angular/cli

# or

yarn add global @angular/cli

The Angular CLI installs the necessary npm packages, creates the project files, and populates the project with a simple default app. Installation can take some time.

Now, create a boilerplate project using the following command.

ng new ngtutorial

Angular 6 Tutorial With Example using Angular CLI

So, now the project is initialized. Go into our project folder. 
cd ngtutorial

Open the project in your editor; I am using VSCode.

code .

Also, start the development server by the following command.

ng serve

Angular 6 Example

Step 2: Install Bootstrap 4 in an Angular app.

Go to your root and install bootstrap 4 using the following command.

yarn add bootstrap

Okay, now copy the bootstrap.min.css file from node_modules/bootstrap/dist/css folder to src/assets/css folder. If the CSS folder is not there, then create one and add that bootstrap.min.css file in it. Now, add the link to that CSS file inside src  >> index.html file.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Ngtutorial</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link href="/assets/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
  <app-root></app-root>
</body>
</html>

Now, you have successfully integrated the Bootstrap 4 Framework.

Step 3: Configure Routing for our components.

Now, create two components using the following command.

ng g c dashboard

Moreover, create another component.

ng g c users

Angular automatically update the app.module.ts file.

Now, Angular is Framework and not just library. So it has Router and Http module already included.

So, first, we will integrate routing for our application.

I am writing the whole code inside app.module.ts file.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { AppComponent } from './app.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { UsersComponent } from './users/users.component';

const routes: Routes = [
  { path: 'users', component: UsersComponent },
  { path: 'dashboard', component: DashboardComponent }
];

@NgModule({
  declarations: [
    AppComponent,
    DashboardComponent,
    UsersComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes)
  ],
  exports: [
    RouterModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

First, we have included the RouterModule and Routes module.

Next, we have created the routes array which is the type of Routes.

That array contains an object, and the properties are following.

  1. path
  2. component

Add an @NgModule.exports array with inRouterModule it. Exporting RouterModule makes router directives available for use in the components AppModule that will need them.

Okay, now we need to display the output of the different routes. For that, we need to define a <router-outlet> component. Also, we need to create a navbar, so that we can easily navigate to different routes and associated components. So, inside app.component.html file, add the following code. It is root component of our Angular application.

<!--The content below is only a placeholder and can be replaced.-->
<div id="app">
    <nav class="navbar navbar-expand-sm bg-light">
        <ul class="navbar-nav">
        <li class="nav-item">
            <a routerLink="/" class="nav-link">Home</a>
        </li>
        <li class="nav-item">
            <a routerLink="/dashboard" class="nav-link">Dashboard</a>
        </li>
        <li class="nav-item">
            <a routerLink="/users" class="nav-link">Users</a>
        </li>
        </ul>
    </nav>
    <div class="container">
        <router-outlet></router-outlet>
    </div>
</div>

Save the file and open the browser and go to http://localhost:4200/

You can see that we have now routing functionality.

Step 4: Create a JSON server that serves the data.

We need the fake data to work with that is why I am using one package called json-server for this tutorial. Okay, so let us install the package using Yarn package manager.

yarn global add json-server

# or

npm install -g json-server

Now we need to create a folder inside src directory called data and in that folder, create one file called db.json. Let us add the following data inside a db.json file.

{
    "results": [
    {
        "id": "1",
        "name": "RDJ",
        "movies": "100"
    },
    {
        "id": "2",
        "name": "Tom Holland",
        "movies": "3"
    },
    {
        "id": "3",
        "name": "Benedict Cumberbatch",
        "movies": "10"
    },
    {
        "id": "4",
        "name": "Chris Hemsworth",
        "movies": "30"
    },
    {
        "id": "5",
        "name": "Chris Evans",
        "movies": "20"
    }]
}

Now, start the JSON server using the following command.

json-server --watch src/data/db.json --port 4000

Now, we have a server running that can feed the data to our Angular Application.

Our JSON server is started at port: 4000 and URL is: http://localhost:4000/results

Step 5: Setup HttpClient.

In other Frontend libraries like React and Vue, we need to install third-party network request library like Axios. However, it is not the case in Angular. Angular is full fledge Frontend Framework, so it has already HTTP module. So first let us configure inside app.module.ts file.

// app.module.ts

import { HttpClientModule } from '@angular/common/http';

 imports: [
    BrowserModule,
    RouterModule.forRoot(routes),
    HttpClientModule,
],

Now, inside users folder, create one file called User.ts. It is an interface, which tells the Angular application that, which kind of data is on the backend that we need to display at frontend.

// User.ts

export interface User {
    id: Number;
    name: String;
    movies: Number;
  }

Also, inside users folder, create one file called user.service.ts. We are writing the network request code inside this file. Then we import this file inside user.component.ts file and then call service file’s function.

// user.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class UserService {
  constructor(private http: HttpClient) { }
  url = 'http://localhost:4000';
  getUsers() {
    return this
            .http
            .get(`${this.url}/results`);
        }
}

Now, include this file inside users.component.ts file.

// users.component.ts

import { Component, OnInit } from '@angular/core';
import { UserService } from './user.service';
import { User } from './User';

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

  users: User[];

  constructor(private userService: UserService) { }

  ngOnInit() {
    this.userService
      .getUsers()
      .subscribe((data: User[]) => {
          this.users = data;
        });
  }

}

Loop through that data and display it as a table inside the users.component.html file.

<table class="table table-striped">
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Movies</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let user of users">
      <td>{{ user.id }}</td>
      <td>{{ user.name }}</td>
      <td>{{ user.movies }}</td>
    </tr>
  </tbody>
</table>

 

Angular HTTP Get request tutorial

So, in this simple tutorial, we have seen the following concepts.

  1. Angular 6 Routing
  2. Angular 6 HTTP Get Request
  3. Angular 6 Service Example

Finally, Angular 6 Tutorial With Example using Angular CLI is over. Thanks for taking this example.

The post Angular 6 Tutorial With Example using Angular CLI appeared first on AppDividend.

]]>
https://appdividend.com/2018/05/05/angular-6-tutorial-with-example-using-angular-cli/feed/ 25