Angular 7 – AppDividend https://appdividend.com Latest Code Tutorials Wed, 20 Mar 2019 19:43:10 +0000 en-US hourly 1 https://wordpress.org/?v=5.1.1 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png Angular 7 – AppDividend https://appdividend.com 32 32 Angular NgFor Tutorial With Example | NgForOf Directive https://appdividend.com/2019/02/12/angular-ngfor-tutorial-with-example-ngforof-directive/ https://appdividend.com/2019/02/12/angular-ngfor-tutorial-with-example-ngforof-directive/#respond Tue, 12 Feb 2019 10:52:01 +0000 http://localhost/wordpress/?p=4703 Angular NgFor Directive Tutorial With Example

Angular NgFor Tutorial With Example | NgForOf Directive is today’s topic. NgFor structural directive renders the template for each item in the collection. The ngForOf is generally used in the shorthand form *ngFor. The core directive ngFor allows us to build data presentation lists and tables in our HTML templates. When we need to display data in Angular, we use the […]

The post Angular NgFor Tutorial With Example | NgForOf Directive appeared first on AppDividend.

]]>
Angular NgFor Directive Tutorial With Example

Angular NgFor Tutorial With Example | NgForOf Directive is today’s topic. NgFor structural directive renders the template for each item in the collection. The ngForOf is generally used in the shorthand form *ngFor. The core directive ngFor allows us to build data presentation lists and tables in our HTML templates. When we need to display data in Angular, we use the ngFor directive.

Angular NgFor Tutorial With Example

Let’s see the Syntax of the NgFor directive.

<ng-template *ngFor="let item of items; index as i; trackBy: trackByFn">...</ng-template>

Let’s take an example of the ngFor directive in Angular.

Step 1: Install Angular

If you do not have the latest Angular CLI, then you need to update your CLI. For more guidance, see this tutorial. Now, create a new project using the following command.

ng new angfor

 

Angular NgFor Tutorial With Example | NgForOf Directive

Now, go inside the folder and open the folder in Visual Studio Code.

Next, install the Bootstrap 4 CSS Framework using the following command.

npm install bootstrap --save

Now, add the bootstrap css file inside the angular.json file.

"styles": [
    "src/styles.css",
    "./node_modules/bootstrap/dist/css/bootstrap.min.css"
],

Step 2: Create a Model file.

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

// Character.ts

export default class Character {
    actor_name: String;
    character_name: String;
    gender: String;
    status: String;
}

We will display the Game of Thrones characters and their properties like actor_name,character_namegenderstatus, etc.

Now, create an array of data inside the app.component.ts file.

// app.component.ts

import { Component } from '@angular/core';
import Character from './Character';
@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   characters: Character[] = [
    {
      actor_name: 'Peter Dinklage',
      character_name: 'Tyrion Lannister',
      gender: 'Male',
      status: 'Alive'
    },
    {
      actor_name: 'Sean Bean',
      character_name: 'Ned Stark',
      gender: 'Male',
      status: 'Dead'
    },
    {
      actor_name: 'Emilia Clark',
      character_name: 'Khaleesi',
      gender: 'Female',
      status: 'Alive'
    },
    {
      actor_name: 'Catelyn Stark',
      character_name: 'Michelle Fairley',
      gender: 'Female',
      status: 'Dead'
    }
  ];
}

So, now we have data that can be rendered inside an HTML view using the ngFor directive.

Step 3: Use a ngFor directive to render HTML table

Let’s create the component so that we can have a working HTML. Write the following code inside an app.component.html file.

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

<div class="container">
  <table class="table table-striped">
    <thead>
        <tr>
          <th>Actor Name</th>
          <th>Character Name</th>
          <th>Gender</th>
          <th>Status</th>
        </tr>
    </thead>
    <tbody>
      <tr *ngFor="let character of characters">
        <td>{{ character.actor_name }}</td>
        <td>{{ character.character_name }}</td>
        <td>{{ character.gender }}</td>
        <td>{{ character.status }}</td>
      </tr>
    </tbody>
  </table>
</div>

Save the file and go to the terminal and start the angular dev server.

ng serve --open

See the output in the browser.

 

Use a ngFor directive to render HTML items

So, the ngFor directive has generated the HTML rows.

This template will generate the HTML table that we showed just above. We can see in this example the (most common) syntax for using ngFor is following.

  • We are passing to ngFor an iteration expression
  • The loop variable named character is defined using the keyword let, which is consistent with Javascript syntax.

Let’s add an index in the table. Write the following code inside an app.component.html file.

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

<div class="container">
  <table class="table table-striped">
    <thead>
        <tr>
          <th>Index</th>
          <th>Actor Name</th>
          <th>Character Name</th>
          <th>Gender</th>
          <th>Status</th>
        </tr>
    </thead>
    <tbody>
      <tr *ngFor="let character of characters; let i = index">
        <td>{{ i+1 }}</td>
        <td>{{ character.actor_name }}</td>
        <td>{{ character.character_name }}</td>
        <td>{{ character.gender }}</td>
        <td>{{ character.status }}</td>
      </tr>
    </tbody>
  </table>
</div>

So, we can add the i as a local variable and display inside the columns using the below code.

<tr *ngFor="let character of characters; let i = index">
        <td>{{ i+1 }}</td>

In the output, we can see the Index, which starts from 1.

Step 4: How to stripe a table using even and odd

NgForOf provides exported values that can be aliased to local variables.

The following exported values can be aliased to local variables.

  1. $implicit: T: The value of all the individual items in the iterable (ngForOf).
  2. ngForOfNgIterable<T>: The value of an iterable expression. Useful when the expression is more complicated then property access, for example when using the async pipe (userStreams | async).
  3. index: number: An index of the current item in the iterable.
  4. first: boolean: True when an item is the first item in the iterable.
  5. last: boolean: True when an item is the last item in the iterable.
  6. even: boolean: True when an item has an even index in the iterable.
  7. odd: boolean: True when an item has an odd index in the iterable.

Now, we use even and odd local variables to differentiate the rows of the table.

We use the NgClass conditional directive. Write the following code inside the app.component.css file. We will define two classes 1) even 2) odd. Then we use those classes based on the even and odd local variable inside the ngFor directive.

.odd {
  background-color: beige;
}
.even {
  background-color: aquamarine;
}

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

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

<div class="container">
  <table class="table table-responsive">
    <thead>
        <tr>
          <th>Index</th>
          <th>Actor Name</th>
          <th>Character Name</th>
          <th>Gender</th>
          <th>Status</th>
        </tr>
    </thead>
    <tbody>
      <tr *ngFor="let character of characters; 
                  let i = index;
                  let even = even; 
                  let odd = odd"
                  [ngClass]="{ odd: odd, even: even }">
        <td>{{ i }}</td>
        <td>{{ character.actor_name }}</td>
        <td>{{ character.character_name }}</td>
        <td>{{ character.gender }}</td>
        <td>{{ character.status }}</td>
      </tr>
    </tbody>
  </table>
</div>

In the above code, see the ngFor directive, we have used the local variables like odd and even. Then we have used the ngClass directive to assign the different classes based on the odd and even values.

Save the file and see the output.

 

How to stripe a table using even and odd

Step 5: Identifying the first and the last row of a table

We have seen the odd and even. Now, see the first and last element.

First, define the two classes inside the app.component.css file.

.first {
  background-color: blanchedalmond;
}
.last {
  background-color: cadetblue;
}

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

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

<div class="container">
  <table class="table table-responsive">
    <thead>
        <tr>
          <th>Index</th>
          <th>Actor Name</th>
          <th>Character Name</th>
          <th>Gender</th>
          <th>Status</th>
        </tr>
    </thead>
    <tbody>
      <tr *ngFor="let character of characters; 
                  let i = index;
                  let first = first; 
                  let last = last"
                  [ngClass]="{ first: first, last: last }">
        <td>{{ i }}</td>
        <td>{{ character.actor_name }}</td>
        <td>{{ character.character_name }}</td>
        <td>{{ character.gender }}</td>
        <td>{{ character.status }}</td>
      </tr>
    </tbody>
  </table>
</div>

So, now it will change the background color of the first and last row. See the output below.

 

Identifying the first and the last row of a table

Finally, the Angular NgFor Tutorial With Example | NgForOf Directive is over.

The post Angular NgFor Tutorial With Example | NgForOf Directive appeared first on AppDividend.

]]>
https://appdividend.com/2019/02/12/angular-ngfor-tutorial-with-example-ngforof-directive/feed/ 0
Angular Modal Tutorial With Example | Angular Material Dialog https://appdividend.com/2019/02/11/angular-modal-tutorial-with-example-angular-material-dialog/ https://appdividend.com/2019/02/11/angular-modal-tutorial-with-example-angular-material-dialog/#comments Mon, 11 Feb 2019 21:29:51 +0000 http://localhost/wordpress/?p=4670 Angular Material Dialog Tutorial Example

Angular Modal Tutorial With Example is today’s topic. We will use Angular Material for this demo. We use Angular 7 for this example. Angular Material is the ground running with significant, modern UI components that work across the web, mobile, and desktop applications. Angular Material components will help us to construct attractive UI and UX, consistent, and functional web pages […]

The post Angular Modal Tutorial With Example | Angular Material Dialog appeared first on AppDividend.

]]>
Angular Material Dialog Tutorial Example

Angular Modal Tutorial With Example is today’s topic. We will use Angular Material for this demo. We use Angular 7 for this example. Angular Material is the ground running with significant, modern UI components that work across the web, mobile, and desktop applications. Angular Material components will help us to construct attractive UI and UX, consistent, and functional web pages and web applications while keeping the modern web design principles like browser portability and compatibility. For this tutorial, I have used the angular material dialog‘s same example, but I have shown step by step from scratch.

Angular Modal Tutorial With Example

The first step is to Install an Angular 7 project.

Step 1: Create an Angular Project

Type the following command.

ng new angularmodal

 

Angular Material Modal

Step 2: Install Angular Material Libraries.

Go inside the project folder and install the hammerjs using the following command.

npm install --save hammerjs

Hammer.js is an optional dependency and helps with touch support for the 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 an angular.json file. You can find this file on the root of the angular project.

Step 3: Create the Custom Material Module File.

Okay, now inside src >> app folder, create one module file called material.module.ts. We have created this material.module.ts file separately because, in future, we can import the different Material components in this file and this file we will import inside the app.module.ts file.

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

// material.module.ts

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

import { MatDialogModule, MatFormFieldModule, MatButtonModule, MatInputModule } from '@angular/material';
import { FormsModule } from '@angular/forms';

@NgModule({
  exports: [FormsModule, MatDialogModule, MatFormFieldModule, MatButtonModule, MatInputModule]
})
export class MaterialModule {}

Here, we have imported the only FormsModule from Angular FormsMatDialogModule, MatFormFieldModule, MatInputModule, and MatButtonModule components from the Angular Material Library.

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

Angular Material comes with some pre-built themes. These themes provide us set off the colors and basic styling. The main available themes are these: indigo-pinkdeeppurple-amberpurple-green and pink-bluegrey. To import the theme in our project, we can add the following code to your global styles.css file. The file is inside the src folder.

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

You can also have access to the Material Design icons and use these 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 and BrowserAnimationsModule files inside the app.module.ts file.

// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MaterialModule } from './material.module';

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

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

Step 5: Angular Material Modal Implementation.

The MatDialog service can be used to open modal dialogs with Material Design styling and animations.

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

// app.component.ts

import { Component, Inject } from '@angular/core';
import {MatDialog, MatDialogRef, MAT_DIALOG_DATA} from '@angular/material';
import { DialogData } from './DialogData';

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

}

Also, create an interface called DialogData.ts file inside the src >> app folder. Write the following code inside that file.

// DialogData.ts

export interface DialogData {
  animal: string;
  name: string;
}

Now, create an Angular Component by typing the following command.

ng g c modal --module app --spec=false

It will create a modal-component folder inside the app folder.

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

// modal.component.ts

import { Component, OnInit, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA} from '@angular/material';
import { DialogData } from '../DialogData';

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

  constructor(
    public dialogRef: MatDialogRef<ModalComponent>,
    @Inject(MAT_DIALOG_DATA) public data: DialogData) {}

  onNoClick(): void {
    this.dialogRef.close();
  }

  ngOnInit() {
  }

}

ModalComponent.ts class is the actual class that implements the Angular Material Modal.

ModalComponent class accepts the DialogData and display inside the dialog. We have used the Dependency Injection to inject the data inside the Angular Dialog.

Write the HTML file of ModalComponent inside the modal.component.html file.

<h1 mat-dialog-title>Hi {{data.name}}</h1>
<div mat-dialog-content>
  <p>What's your favorite animal?</p>
  <mat-form-field>
    <input matInput [(ngModel)]="data.animal">
  </mat-form-field>
</div>
<div mat-dialog-actions>
  <button mat-button (click)="onNoClick()">No Thanks</button>
  <button mat-button [mat-dialog-close]="data.animal" cdkFocusInitial>Ok</button>
</div>

In this HTML file, we have used the Material Modules and Angular Form modules which we have imported earlier inside the material.module.ts file.

Above HTML will be shown, when a user clicks on the button that pops up the Modal.

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

// app.component.ts

import { Component, Inject } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { ModalComponent } from './modal/modal.component';

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

  constructor(public dialog: MatDialog) {}

  openDialog(): void {
    const dialogRef = this.dialog.open(ModalComponent, {
      width: '250px',
      data: {name: this.name, animal: this.animal}
    });

    dialogRef.afterClosed().subscribe(result => {
      this.animal = result;
    });
  }
}

First, we have imported the ModalComponent inside the app.component.ts file.

Then we have created one function called openDialog() which will open the ModalComponent.

We have passed the data like name and animal to that ModalComponent.

When the user closes the ModalComponent, AppComponent gets the value of animal which we have typed inside the ModalComponent and display inside the AppComponent file.

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

<div>
  <ol>
    <li>
      <mat-form-field>
        <input matInput [(ngModel)]="name" placeholder="What's your name?">
      </mat-form-field>
    </li>
    <li>
      <button mat-raised-button (click)="openDialog()">Pick one</button>
    </li>
    <br />
    <li *ngIf="animal">
      You chose: <p style="font-weight: bold">{{animal}}</p>
    </li>
  </ol>
</div>

Here, you can see that we have passed the data between AppComponent and ModalComponent. The data is name and animal.

If the user has typed the animal name inside the ModalComponent, then after the closing of Modal, we can see the animal name inside the AppComponent.

Still, there is one thing missing which is the entryComponents of the Angular application which we need to define inside the app.module.ts file. So, our final app.component.ts file looks like below.

// app.component.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MaterialModule } from './material.module';

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

@NgModule({
  declarations: [AppComponent, ModalComponent],
  imports: [BrowserModule, BrowserAnimationsModule, MaterialModule],
  providers: [],
  bootstrap: [AppComponent],
  entryComponents: [ModalComponent]
})
export class AppModule {}

Finally, save the file and start the angular dev server by the following command.

ng serve --open

It will open the browser, and you can see something like below.

 

Angular Material Modal Implementation.

Now, first, type your name and click the button pick one and you will see the Angular Material Dialog.

 

Angular Modal Tutorial With Example | Angular Material Dialog

Now, if you press the Ok and if you have typed the animal name then you will see something like below.

 

Angular Modal Tutorial With Example

So, we have successfully implemented the Angular Material Modal or Angular Modal or Angular Material Dialog. You can find more details about the Angular Material Dialog here.

Finally, Angular Modal Tutorial With Example | Angular Material Dialog is over.

Github Code

The post Angular Modal Tutorial With Example | Angular Material Dialog appeared first on AppDividend.

]]>
https://appdividend.com/2019/02/11/angular-modal-tutorial-with-example-angular-material-dialog/feed/ 1
Angular 7 NgStyle Tutorial With Example | Angular NgStyle https://appdividend.com/2019/02/11/angular-7-ngstyle-tutorial-with-example-angular-ngstyle/ https://appdividend.com/2019/02/11/angular-7-ngstyle-tutorial-with-example-angular-ngstyle/#respond Mon, 11 Feb 2019 09:44:16 +0000 http://localhost/wordpress/?p=4657 Angular ngStyle Tutorial With Example

Angular 7 NgStyle Tutorial With Example | Angular NgStyle is today’s topic. An attribute directive that updates styles for the containing HTML element. Sets one or more style properties, specified as colon-separated key-value pairs. The NgStyle directive lets you set a given DOM element’s style properties. The key is a style name, and the value is an expression to be evaluated.  The resulting non-null […]

The post Angular 7 NgStyle Tutorial With Example | Angular NgStyle appeared first on AppDividend.

]]>
Angular ngStyle Tutorial With Example

Angular 7 NgStyle Tutorial With Example | Angular NgStyle is today’s topic. An attribute directive that updates styles for the containing HTML element. Sets one or more style properties, specified as colon-separated key-value pairs. The NgStyle directive lets you set a given DOM element’s style properties. The key is a style name, and the value is an expression to be evaluated.  The resulting non-null value, expressed in the given unit, is assigned to the given style property. If the result of the evaluation is null, the corresponding style is removed.

Angular 7 NgStyle Tutorial

If you do not have the latest Angular CLI, then you need to update your CLI. For more guidance, see this tutorial. Now, create a new project using the following command.

ng new angulardata

Now, go inside the folder and open the folder in Visual Studio Code.

Next, install the Bootstrap 4 CSS Framework using the following command. You can skip the step of installing bootstrap because we do not need too much of styling here.

npm install bootstrap --save

Now, add the bootstrap css file inside the angular.json file.

"styles": [
    "src/styles.css",
    "./node_modules/bootstrap/dist/css/bootstrap.min.css"
],

Step 1: Create a Model file.

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

// Character.ts

export default class Character {
    actor_name: String;
    character_name: String;
    gender: String;
    status: String;
}

We will display the Game of Thrones characters and their properties like actor_name,character_namegenderstatus, etc.

Now, create an array of data inside the app.component.ts file.

// app.component.ts

import { Component } from '@angular/core';
import Character from './Character';
@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   characters: Character[] = [
    {
       actor_name: 'Peter Dinklage',
       character_name: 'Tyrion Lannister',
       gender: 'Male',
       status: 'Alive'
    },
    {
       actor_name: 'Sean Bean',
       character_name: 'Ned Stark',
       gender: 'Male',
       status: 'Dead'
    },
    {
       actor_name: 'Emilia Clark',
       character_name: 'Khaleesi',
       gender: 'Female',
       status: 'Alive'
    },
    {
       actor_name: 'Catelyn Stark',
       character_name: 'Michelle Fairley',
       gender: 'Female',
       status: 'Dead'
    }
  ];
}

Step 2: Create HTML view to display data in Angular

Now, the last step is to write the HTML code to display the data.

We will first display the data in Table Format.

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

<div class="container">
  <h4>NgStyle</h4>
  <div *ngFor="let celeb of characters">
     <p [ngStyle]="{'background-color':celeb.status === 'Dead' ? 'red' : 'green' }">
	{{ celeb.actor_name }} ({{ celeb.character_name }}) is {{celeb.gender}} character and {{celeb.status}}
     </p>
   </div>
</div>

In the above code, we have looped through the characters data and display the data one by one.

Here, we have used the ngStyle directive to assign the style to the P element.

We have assigned conditional styling. So, if the character is dead then it will show background color red otherwise green. So, we have applied the conditional styling using the ngStyle directive in Angular.

Save the file and see the output in the browser.

 

Angular 7 NgStyle Tutorial With Example | Angular NgStyle

Angular ngStyle becomes much more useful when the value is dynamic. The values in the object literal that we assign to ngStyle can be javascript expressions which are evaluated and the result of that expression is used as the value of the css property.

We can assign the following type of styling to the HTML elements using the ngStyle directive.

Set the font of the containing element to the result of an expression.

<some-element [ngStyle]="{'font-style': styleExp}">...</some-element>

Set the width of the containing element to a pixel value returned by an expression.

<some-element [ngStyle]="{'max-width.px': widthExp}">...</some-element>

Set a collection of style values using an expression that returns key-value pairs.

<some-element [ngStyle]="objExp">...</some-element>

Finally, Angular 7 NgStyle Tutorial With Example | Angular NgStyle is over.

The post Angular 7 NgStyle Tutorial With Example | Angular NgStyle appeared first on AppDividend.

]]>
https://appdividend.com/2019/02/11/angular-7-ngstyle-tutorial-with-example-angular-ngstyle/feed/ 0
How To Display Data In Angular | Angular 7 Display Data https://appdividend.com/2019/02/09/how-to-display-data-in-angular-7-display-data/ https://appdividend.com/2019/02/09/how-to-display-data-in-angular-7-display-data/#respond Sat, 09 Feb 2019 18:14:48 +0000 http://localhost/wordpress/?p=4641 Angular 7 Display Data in Table Format

How To Display Data In Angular | Angular 7 Display Data is today’s topic. We can display the data in whatever format we want. The general use case is to display the data in tabular format means in table format. In real Angular app, the data is dynamic coming from the backend API. So, we […]

The post How To Display Data In Angular | Angular 7 Display Data appeared first on AppDividend.

]]>
Angular 7 Display Data in Table Format

How To Display Data In Angular | Angular 7 Display Data is today’s topic. We can display the data in whatever format we want. The general use case is to display the data in tabular format means in table format. In real Angular app, the data is dynamic coming from the backend API. So, we need to display the data in a proper format so that the user can interact properly. For this example, we will take a static data defined in an array format and then display that data on the frontend using the ngFor loop.

How To Display Data In Angular

If you are new to Angular 7, then check out this Angular 7 CRUD Tutorial article. In that tutorial also, I have displayed the data in the Frontend using the ngFor loop, but this tutorial is specific, how to display data. Let’s see one by one step to display data in Angular 7.

Step 1: Install Angular 7 Application

If you do not have the latest Angular CLI, then you need to update your CLI. For more guidance, see this tutorial.

Now, create a new project using the following command.

 

How To Display Data In Angular

Now, go inside the folder and open the folder in Visual Studio Code.

Next, install the Bootstrap 4 CSS Framework using the following command.

npm install bootstrap --save

Now, add the bootstrap css file inside the angular.json file.

"styles": [
    "src/styles.css",
    "./node_modules/bootstrap/dist/css/bootstrap.min.css"
],

Step 2: Create a Model file.

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

// Character.ts

export default class Character {
    actor_name: String;
    character_name: String;
    gender: String;
    status: String;
}

We will display the Game of Thrones characters and their properties like actor_name, character_name, gender, status, etc.

Now, create an array of data inside the app.component.ts file.

// app.component.ts

import { Component } from '@angular/core';
import Character from './Character';
@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   characters: Character[] = [
    {
	actor_name: 'Peter Dinklage',
	character_name: 'Tyrion Lannister',
	gender: 'Male',
        status: 'Alive'
    },
    {
	actor_name: 'Sean Bean',
	character_name: 'Ned Stark',
	gender: 'Male',
	status: 'Dead'
    },
    {
	actor_name: 'Emilia Clark',
	character_name: 'Khaleesi',
	gender: 'Female',
	status: 'Alive'
    },
    {
	actor_name: 'Catelyn Stark',
	character_name: 'Michelle Fairley',
	gender: 'Female',
	status: 'Dead'
    }
  ];
}

Step 3: Create HTML view to display data in Angular

Now, the last step is to write the HTML code to display the data.

We will first display the data in Table Format.

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

<div class="container">
  <table class="table table-striped">
    <thead>
        <tr>
          <th>Actor Name</th>
          <th>Character Name</th>
          <th>Gender</th>
          <th>Status</th>
        </tr>
    </thead>
    <tbody>
      <tr *ngFor="let character of characters">
        <td>{{ character.actor_name }}</td>
        <td>{{ character.character_name }}</td>
        <td>{{ character.gender }}</td>
        <td>{{ character.status }}</td>
      </tr>
    </tbody>
  </table>
</div>

Now, in this code, we have used the *ngFor to display the characters one by one.

Save the file and go to the terminal and hit the following command.

ng serve --open

It will open up the browser and open this URL: http://localhost:4200.

See the below output.

 

How To Display Data In Angular | Angular 7 Display Data

We can also display the output in the unordered list. See the following HTML code.

<div class="container">  
  <ul *ngFor="let character of characters">
    <li>{{ character.actor_name }}</li>
    <li>{{ character.character_name }}</li>
    <li>{{ character.gender }}</li>
    <li>{{ character.status }}</li>
  </ul>
</div>

Now, it will display the data in the unordered list.

In a real-life scenario, mostly we will display data in table format.

Finally, How To Display Data In Angular | Angular 7 Display Data Tutorial is over.

The post How To Display Data In Angular | Angular 7 Display Data appeared first on AppDividend.

]]>
https://appdividend.com/2019/02/09/how-to-display-data-in-angular-7-display-data/feed/ 0
Angular 7 NgClass Tutorial With Example | Angular NgClass https://appdividend.com/2019/02/07/angular-7-ngclass-tutorial-with-example-angular-ngclass/ https://appdividend.com/2019/02/07/angular-7-ngclass-tutorial-with-example-angular-ngclass/#respond Thu, 07 Feb 2019 12:48:32 +0000 http://localhost/wordpress/?p=4627 Angular NgClass Example Tutorial

Angular 7 NgClass Tutorial With Example | Angular NgClass is today’s topic. If you are new to Angular 7, then check out this Angular 7 CRUD Tutorial article. Angular NgClass adds and removes CSS classes on an HTML element. The NgClass directive in Angular allows you to set the CSS class dynamically for the DOM element. The NgClass directive behaves very similar to what ngClass used to do in AngularJS. Angular 7 NgClass […]

The post Angular 7 NgClass Tutorial With Example | Angular NgClass appeared first on AppDividend.

]]>
Angular NgClass Example Tutorial

Angular 7 NgClass Tutorial With Example | Angular NgClass is today’s topic. If you are new to Angular 7, then check out this Angular 7 CRUD Tutorial article. Angular NgClass adds and removes CSS classes on an HTML element. The NgClass directive in Angular allows you to set the CSS class dynamically for the DOM element. The NgClass directive behaves very similar to what ngClass used to do in AngularJS.

Angular 7 NgClass Tutorial With Example

You can update the CSS classes based on the type of the expression selection.

  1. string – The CSS classes listed in the string (space delimited) are added,
  2. Array – The CSS classes declared as the Array elements are added,
  3. Object – The keys are CSS classes that get added when the expression given in the value evaluates to the true value. If false, then they are removed.

The selector of NgClass directive is [ngClass]. Depending on the type of evaluation, we will assign the class values to this ngClass directive.

Okay, now let’s see the NgClass directive in Action.

Step 1: Install Angular 7 Application

If you do not have latest Angular CLI, then you need to update your CLI. For more guidance, see this tutorial.

Now, create a new project using the following command.

 

Install Angular 7 Application

Now, go inside the folder and open the folder in Visual Studio Code.

Next, install the Bootstrap 4 CSS Framework using the following command.

npm install bootstrap --save

Now, add the bootstrap css file inside the angular.json file.

"styles": [
    "src/styles.css",
    "./node_modules/bootstrap/dist/css/bootstrap.min.css"
],

Step 2: Create a Model file.

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

// Singer.ts

export default class Singer {
    artist: String;
    country: String;
}

So, our data array has two properties. 1) artist 2) country.

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

// app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
    singers: Singer[] = [
       {
	  'artist': 'Michael Jackson',
	  'country': 'USA'
	},
	{
	  'artist': 'Justin Bieber',
	  'country': 'Canada'
	},
	{
	  'artist': 'Daddy Yankee',
	  'country': 'Purto Rico'
	},
	{
	   'artist': 'A R Rehman',
	    'country': 'India'
	},
	{
	    'artist': 'Selena Gomez',
	    'country': 'USA'
	}
   ];
}

So, here based on data, we assign the classes to the HTML page and to do that, we need to use the NgClass directive.

Step 3: Put NgClass directive on HTML page

In the app.component.html file, we need a conditional rendering.

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

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

<div class="container">
<h4>NgClass</h4>
<div *ngFor="let celeb of singers">
  <p [ngClass]="{
    'text-success':celeb.country === 'USA',
    'text-secondary':celeb.country === 'Canada',
    'text-danger':celeb.country === 'Puorto Rico',
    'text-info':celeb.country === 'India'
  }">{{ celeb.artist }} ({{ celeb.country }})
</p>
</div>
</div>

Here, we have used the Object valuation where keys are CSS classes that get added when the expression given in the value evaluates to a truthy value. Otherwise, they are removed.

I have compared the Singer’s country and if match then it will assign that particular text class.

Save the file and go to the terminal and start the Angular development server.

ng serve --open

It will open the browser, and now you can see that according to Singer’s country, we can see the different text color.

 

Angular 7 NgClass Tutorial With Example | Angular NgClass

Finally, Angular 7 NgClass Tutorial With Example | Angular NgClass is over.

The post Angular 7 NgClass Tutorial With Example | Angular NgClass appeared first on AppDividend.

]]>
https://appdividend.com/2019/02/07/angular-7-ngclass-tutorial-with-example-angular-ngclass/feed/ 0
Angular Material Icon Tutorial With Example https://appdividend.com/2018/12/25/angular-material-icon-tutorial-with-example/ https://appdividend.com/2018/12/25/angular-material-icon-tutorial-with-example/#respond Tue, 25 Dec 2018 08:53:27 +0000 http://localhost/wordpress/?p=2860 Angular 7 Material Icon and Custom SVG Icons tutorial example

Angular Material Icon Tutorial With Example is today’s topic. The Angular Material library has a wide variety of components that we can use. One such component is <mat-icon>. The <mat-icon> component makes it easier to use vector-based icons in your angular app. This directive supports both icon fonts and SVG icons, but not bitmap-based formats. In this Angular Material […]

The post Angular Material Icon Tutorial With Example appeared first on AppDividend.

]]>
Angular 7 Material Icon and Custom SVG Icons tutorial example

Angular Material Icon Tutorial With Example is today’s topic. The Angular Material library has a wide variety of components that we can use. One such component is <mat-icon>. The <mat-icon> component makes it easier to use vector-based icons in your angular app. This directive supports both icon fonts and SVG icons, but not bitmap-based formats. In this Angular Material Icon Tutorial, we will see how we can display the existing material icon provided by the library and also see how we can add our SVG icon to the material app.

If you want to learn more about the latest Javascript tutorials then check out this The Complete Javascript Course 2018.

Angular Material Icon Tutorial With Example

Let us start by installing an Angular project and configure the Material library in Angular.

Step 1: Install and configure Angular Material

Type the following command. I am using Angular 7 for this demo.

ng new angicon

 

Angular Material Icon Tutorial With Example

Now, go to the project and install the hammerjs.

npm install --save hammerjs

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 an angular.json file on the root of the project.

"scripts": [
     "./node_modules/hammerjs/hammer.min.js"
]

Import a pre-built theme and Material icons.

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

@import '~@angular/material/prebuilt-themes/indigo-pink.css';
@import url("https://fonts.googleapis.com/icon?family=Material+Icons");

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

// app.module.ts

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

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

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

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

Step 2: Import MatIconModule module

Okay, now we need to import the MatIconModule inside the app.module.ts file.

// app.module.ts

import { MatIconModule } from '@angular/material/icon';

@NgModule({
  declarations: [
    AppComponent,
    ...
  ],
  imports: [
    ...
    MatIconModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

We can use the built-in material icons with the <mat-icon> component. So modify the app.component.html file like below.

<div style="text-align:center">
  <h1>
    Welcome to Angular Material App <mat-icon>mood</mat-icon>
  </h1>
</div>

Go to the terminal and start the angular development server.

ng serve --open

 

Angular 7 Material Icon Tutorial

So, we have successfully integrated the Angular Material Icon inside Angular demo application.

MatIconRegistry is an injectable service that allows us to associate icon names with the SVG URLs, HTML strings and to define aliases for CSS font classes.

Service to register and display icons used by the <mat-icon> component.

  1. Registers icon URLs by namespace and name.
  2. Registers icon set URLs by namespace.
  3. Registers aliases for CSS classes, for use with icon fonts.
  4. Loads icons from URLs and extracts individual icons from icon sets.

When the <mat-icon> component displays an SVG icon, it does so by directly inlining an SVG content into the page as the child of a component rather than use the tag or a div background image.

How To Use Custom SVG Icons

We can also use the custom SVG icons inside our app. I have downloaded one SVG icon for an airplane. Let us use that icon inside our Angular Material tutorial.

Now, copy that icon inside src >> assets folder.

To use our custom airplane icon with the <mat-icon> component tag, we need to add the HttpClientModule inside the app.module.ts file. That is why import the module inside the app.module.ts file.

// app.module.ts

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

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatIconModule } from '@angular/material/icon';
import { HttpClientModule } from '@angular/common/http';

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

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

Now, we need to register our custom icon with the MatIconRegistry service provided by Angular Material package.

Import the MatIconRegistry and inject the service into your component. In the component’s constructor method.  The addSvgIcon registers our icon by taking-in two arguments, the first one is being the icon label which is of type string. The second argument is the relative URL path pointing to the location of the icon. This is a type of SafeResourceUrl. To parse the url path string into SafeResourceUrl, we can make use of the DomSanitizer module provided by Angular. Import DomSanitizer and inject it into your component. So, our final code will look like this inside the app.component.ts file.

// app.component.ts

import { Component } from '@angular/core';
import { MatIconRegistry } from '@angular/material/icon';
import { DomSanitizer } from '@angular/platform-browser';

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

    constructor(
            private matIconRegistry: MatIconRegistry,
            private domSanitizer: DomSanitizer) {
        this.matIconRegistry.addSvgIcon(
            'airplane',
            this.domSanitizer.bypassSecurityTrustResourceUrl('../assets/airplane.svg')
        );
    }
}

So, here we have successfully registered the custom SVG icon inside our Angular app. The last step is to use the airplane.svg icon inside the app.component.html file.

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

<div style="text-align:center">
  <h1>
    <mat-icon svgIcon="airplane"></mat-icon>
    <mat-icon svgIcon="airplane"></mat-icon>
    <mat-icon svgIcon="airplane"></mat-icon>
    <mat-icon svgIcon="airplane"></mat-icon>
    <mat-icon svgIcon="airplane"></mat-icon>
  </h1>
</div>

Save the file and go to the http://localhost:4200/ and you can see that five svg icons will be displayed. So that is how you can import the custom svg icons inside an angular example.

How To Use Custom SVG Icons in Angular

 

Finally, Angular Material Icon Tutorial With Example is over. You can find more about Angular Material Icons here. I have put the code on Github; please check that out as well.

Github Code

The post Angular Material Icon Tutorial With Example appeared first on AppDividend.

]]>
https://appdividend.com/2018/12/25/angular-material-icon-tutorial-with-example/feed/ 0
Angular 7 Drag and Drop Tutorial With Example https://appdividend.com/2018/12/22/angular-7-drag-and-drop-tutorial-example/ https://appdividend.com/2018/12/22/angular-7-drag-and-drop-tutorial-example/#comments Sat, 22 Dec 2018 06:08:50 +0000 http://localhost/wordpress/?p=2849 Angular Drag and Drop Functionality Tutorial

Angular 7 Drag and Drop Tutorial With Example is today’s leading topic.  We will use Angular 7 and Angular Material 7 for this example.  Angular Material is the ground running with significant, modern UI components. Angular Material Design components will help us to construct attractive UI and UX, consistent, and functional web pages and web applications while keeping modern web design principles like browser portability […]

The post Angular 7 Drag and Drop Tutorial With Example appeared first on AppDividend.

]]>
Angular Drag and Drop Functionality Tutorial

Angular 7 Drag and Drop Tutorial With Example is today’s leading topic.  We will use Angular 7 and Angular Material 7 for this example.  Angular Material is the ground running with significant, modern UI components. Angular Material Design components will help us to construct attractive UI and UX, consistent, and functional web pages and web applications while keeping modern web design principles like browser portability and compatibility. In today’s post, we will use the DragDropModule in the Angular Material library. So let us start an Angular 7 Drag and Drop Tutorial With Example From Scratch.

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

Angular 7 Drag and Drop Tutorial With Example

Let us create an Angular 7 project. If you have Angular CLI 6, then you need to upgrade your CLI. For that, you can refer to this article.

#1: Install Angular 7 project and Angular Material Library

ng new ang7drag

 

Angular 7 Drag and Drop Tutorial With Example

Now, go into the project folder and open the project inside the visual studio code.

cd ang7drag
code .

Install the hammerjs using the following command.

npm install --save hammerjs

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

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

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

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

"scripts": [
     "./node_modules/hammerjs/hammer.min.js"
]

#3: Import the pre-built theme and Material icons

Angular Material comes with some pre-built themes. These themes provide us set off the colors and basic styling. The main available themes are these: indigo-pinkdeeppurple-amberpurple-green and pink-bluegrey. To import the theme in our project, we can add the following code to your global styles.css file. The file is inside the src folder.

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

You can also have access to the Material Design icons and use these 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 BrowserAnimationsModule inside the app.module.ts file.

// app.module.ts

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

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

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

#4: API reference for Angular CDK drag-drop

We need to import the DragDropModule inside the app.module.ts file.

// app.module.ts

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { DragDropModule } from '@angular/cdk/drag-drop';

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

It is the container that wraps a set of draggable items.

Selector: [cdkDropList] cdk-drop-list

Exported as: cdkDropList

Methods

It has the drop() method. It drops an item into this container.

Parameters

item

CdkDrag<any>

The item is dropped into the container.

currentIndex

number

Index at which the item should be inserted.
previousContainer

Partial<CdkDropListContainer<any>>

Container from which the item got dragged in.

isPointerOverContainer

boolean

Whether the user’s pointer was over the container when the item was dropped.

 

#5: Create a service and model files

Create an Angular service using the following command.

ng g s student --spec=false

It will create a file student.service.ts file inside the src >> app folder.

We have created service because we will use service to handle the data that needs to be displayed on the frontend.

Also, create a new file inside the src >> app folder called student.model.ts and add the following code inside it.

// student.model.ts

export class Student {
    name: String;
}

Now, we need to add the demo data inside the student.service.ts file. The data is the type of Student model which we have defined above.

// student.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Student } from './student.model';

@Injectable({
  providedIn: 'root'
})
export class StudentService {

    students: Student[] = [
    {
        name: 'Krunal'
    },
    {
        name: 'Ankit'
    },
    {
        name: 'Rushabh'
    },
    {
        name: 'Dhaval'
    },
    {
        name: 'Nehal'
    },

  constructor() { }

  public getStudents(): any {
     const studentsObservable = new Observable(observer => {
            setTimeout(() => {
                observer.next(this.students);
            }, 1000);
     });

     return studentsObservable;
 }
}

So, here we have done is first import the Observable from rxjs. Then defined one function that will return an observable. The observable object gets one argument that has a timeout function. So after 1 second, it will produce the whole student’s array if the subscriber subscribes the observable.

In simple terms, here studentObservable are publishing our primary data array that is students. So if any entity needs to get the values out of observable, then it first needs to subscribe that observable and then studentObservable starts to publish the values, and then subscriber get the values.

#6: Define the Subscriber

We have created the Publisher for the Observables. Now, we need to create a subscriber. So write the following code inside the app.component.ts file.

// app.component.ts

import { Component, OnInit } from '@angular/core';
import {CdkDragDrop, moveItemInArray} from '@angular/cdk/drag-drop';
import { Student } from './student.model';
import { StudentService } from './student.service';

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

    constructor(private studentservice: StudentService) {}

    drop(event: CdkDragDrop<string[]>) {
        moveItemInArray(this.students, event.previousIndex, event.currentIndex);
    }

    ngOnInit() {
        const studentsObservable = this.studentservice.getStudents();
        studentsObservable.subscribe((studentsData: Student[]) => {
            this.students = studentsData;
        });
    }
}

So, when the component Initializes, we will call the service method’s getStudents() methods and fetch all the student names in an array.

Now, we need to create the drop() method which is provided by CdkDragDrop module. Also, we are calling the moveItemInArray which takes three arguments, and we pass that students array to that list.

#7: Add CSS and HTML code

Now, we need to add the CSS3 classes inside the app.component.css file. So let us do that. 
.example-list {
    width: 500px;
    max-width: 100%;
    border: solid 1px #ccc;
    min-height: 60px;
    display: block;
    background: white;
    border-radius: 4px;
    overflow: hidden;
  }
  
  .example-box {
    padding: 20px 10px;
    border-bottom: solid 1px #ccc;
    color: rgba(0, 0, 0, 0.87);
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    box-sizing: border-box;
    cursor: move;
    background: white;
    font-size: 14px;
  }
  
  .cdk-drag-preview {
    box-sizing: border-box;
    border-radius: 4px;
    box-shadow: 0 5px 5px -3px rgba(0, 0, 0, 0.2),
                0 8px 10px 1px rgba(0, 0, 0, 0.14),
                0 3px 14px 2px rgba(0, 0, 0, 0.12);
  }
  
  .cdk-drag-placeholder {
    opacity: 0;
  }
  
  .cdk-drag-animating {
    transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
  }
  
  .example-box:last-child {
    border: none;
  }
  
  .example-list.cdk-drop-list-dragging .example-box:not(.cdk-drag-placeholder) {
    transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
  }

It will help us to transform the HTML elements. Now, the final step is to add the HTML code inside the app.component.html file.

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

<div cdkDropList class="example-list" (cdkDropListDropped)="drop($event)">
    <div class="example-box" *ngFor="let student of students" cdkDrag>{{ student.name }}</div>
</div>

Save the file and start the angular dev server.

ng serve --open

 

Angular 7 Drag and Drop Tutorial

You will see something like this and now you can able to drag and drop the items inside that box.

The cdkDropList directive supports transferring dragged items between connected drop zones. You can connect one or more cdkDropList instances together by setting the cdkDropListConnectedTo property or by wrapping the elements in an element with the cdkDropListGroup attribute.

Okay, now we will create the two section and we can interchange the lists between that two sections.

So, we need to create a second array called students2. We will define that array inside the app.component.ts file and do not go for services.

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

// app.component.ts

import { Component, OnInit } from '@angular/core';
import {CdkDragDrop, moveItemInArray, transferArrayItem} from '@angular/cdk/drag-drop';
import { Student } from './student.model';
import { StudentService } from './student.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
    students: Student[] = [];
    students2: Student[] = [
        {
            name: 'Siddharth'
        },
        {
            name: 'Jay'
        },
        {
            name: 'Jaydeep'
        },
        {
            name: 'Chirag'
        }];
    constructor(private studentservice: StudentService) {}

    drop(event: CdkDragDrop<string[]>) {
        if (event.previousContainer === event.container) {
            moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
        } else {
        transferArrayItem(event.previousContainer.data,
                        event.container.data,
                        event.previousIndex,
                        event.currentIndex);
        }
    }

    ngOnInit() {
        const studentsObservable = this.studentservice.getStudents();
        studentsObservable.subscribe((studentsData: Student[]) => {
            this.students = studentsData;
        });
    }
}

Also, we need to modify the app.component.html code.

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

<div class="example-container">
    <h2>Students</h2>
    <div
      cdkDropList
      #studentsList="cdkDropList"
      [cdkDropListData]="students"
      [cdkDropListConnectedTo]="[students2List]"
      class="example-list"
      (cdkDropListDropped)="drop($event)">
      <div class="example-box" *ngFor="let student of students" cdkDrag>{{student.name}}</div>
    </div>
  </div>
  
  <div class="example-container">
    <h2>Students 2</h2>
    <div
      cdkDropList
      #students2List="cdkDropList"
      [cdkDropListData]="students2"
      [cdkDropListConnectedTo]="[studentsList]"
      class="example-list"
      (cdkDropListDropped)="drop($event)">
      <div class="example-box" *ngFor="let student2 of students2" cdkDrag>{{student2.name}}</div>
  </div>
</div>

Save the file and go to the browser and you will see something like this.

Angular Drag and Drop Example
Finally, Angular 7 Drag and Drop Tutorial With Example is over.

The post Angular 7 Drag and Drop Tutorial With Example appeared first on AppDividend.

]]>
https://appdividend.com/2018/12/22/angular-7-drag-and-drop-tutorial-example/feed/ 3
Angular 7 Architecture Overview https://appdividend.com/2018/12/21/angular-7-architecture-overview/ https://appdividend.com/2018/12/21/angular-7-architecture-overview/#comments Fri, 21 Dec 2018 17:07:10 +0000 http://localhost/wordpress/?p=2837 Angular 7 Architecture Overview

In today’s post, we will see Angular 7 Architecture Overview. Angular is a platform and framework for building client applications in HTML and TypeScript. Typescript is a superset of Javascript. Angular is written in TypeScript. It implements core and optional functionality as a set of TypeScript libraries that you import into your apps. The pioneer building blocks of […]

The post Angular 7 Architecture Overview appeared first on AppDividend.

]]>
Angular 7 Architecture Overview

In today’s post, we will see Angular 7 Architecture Overview. Angular is a platform and framework for building client applications in HTML and TypeScript. Typescript is a superset of Javascript. Angular is written in TypeScript. It implements core and optional functionality as a set of TypeScript libraries that you import into your apps. The pioneer building blocks of the Angular application are NgModules, which provide the compilation context for components.

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

Angular 7 Architecture Overview

We can identify the following main building blocks of an Angular Application.

  1. Modules
  2. Components
  3. Templates
  4. Metadata
  5. Data binding
  6. Directives
  7. Services
  8. Dependency Injection

A set of NgModules defines the angular app, and it always has at least a root module that enables bootstrapping, and many more feature modules.

  1. Components define Template views
  2. Components use services

The Angular Module (NgModules) helps us to organize an application into connected blocks of functionality.

Angular 7 Modules

Every Angular app has a root module, conventionally named AppModule, which provides the bootstrap mechanism that launches the application. An app typically contains many functional modules.

// app.module.ts

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

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

If we want to use another custom Angular module, then we need to register that module inside the app.module.ts file. Organizing your code into distinct functional modules helps in managing the development of complex applications, and in designing for reusability.

Angular 7 Components

Every Angular project has at least one component, the root component and root component connects the component hierarchy with a page document object model (DOM). Each component defines the class that contains application data and logic, and it is associated with the HTML template that defines the view to be displayed in a target app.

The @Component decorator identifies the class immediately below it as the component and provides the template and related component-specific metadata.

// app.component.ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

Angular 7 Templates

The angular template combines the HTML with Angular markup that can modify HTML elements before they are displayed. Template directives provide program logic, and binding markup connects your application data and the DOM. There are two types of data binding.

  • Event binding lets your app respond to user input in the target environment by updating your application data.
  • Property binding lets you interpolate values that are computed from your application data into the HTML.
<div style="text-align:center">
  <h1>
    {{2 | power: 5}}
  </h1>
</div>

In the above HTML file, we have used a template. We have also used the pipe inside the template to transform the values to the desired output.

Angular 7 Metadata

Metadata is used to decorate the class so that it can configure the expected behavior of a class. Decorators are the core concept when developing with Angular (versions 2 and above). The user can use metadata to a class to tell Angular app that AppComponent is the component. Metadata can be attached to the TypeScript using the decorator.

// app.component.ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

@Component is a decorator which makes use of configuration object to create the component and its view.

Angular 7 Data Binding

Angular allows defining communication between a component and the DOM, making it very easy to define interactive applications without worrying about pulling and pushing the data.

From the Component to the DOM

Interpolation: {{ value }}: Interpolation adds the value of the property from the component.

<p>Name: {{ student.name }}</p>
<p>College: {{ student.college }}</p>

Property binding: [property]=”value”

With property binding, a value is passed from a component to a specified property, which can often be a simple html attribute.

<input type="text" [value]="student.name" />
<input type="text" [value]="student.college" />

Angular 7 Directives

An Angular component isn’t more than a directive with the template. When we say that components are the building blocks of Angular applications, we are saying that directives are the building blocks of Angular projects. Let us use built-in Angular directive like ngClass, which is a better example of the existing Angular attribute directive.

<p [ngClass]="{'coffee'=true, 'red'=false}">
    Angular 7 Directives Example 
</p>

<style>
    .coffee{color: coffee}
    .red{color: red}
</style>

Here, based on the [ngClass] directive’s value, the text has color. In our example, the text will be coffee because it is true.

Angular 7 Services

For data or logic that isn’t associated with a specific view, and that you want to share across components, you create a service class. The @Injectable decorator immediately precedes the service class definition. The decorator provides the metadata that allows your service to be injected into client components as a dependency. Angular distinguishes components from services to increase modularity and reusability. By separating a component’s view-related functionality from other kinds of processing, you can make your component classes lean and efficient.

Angular 7 Dependency Injection

Dependency injection (DI) lets you keep your component classes lean and efficient. DI does not fetch data from a server, validate the user input, or log directly to the console instead they delegate such tasks to the services. DI is wired into a Angular framework and used everywhere to provide new components with the services or other things they need. Components consume services; that is, you can inject a service into a component, giving the component access to that service class.

So these are the building blocks of Angular. Angular 7 Architecture Overview is over.

The post Angular 7 Architecture Overview appeared first on AppDividend.

]]>
https://appdividend.com/2018/12/21/angular-7-architecture-overview/feed/ 1
Angular 7 Pipes Tutorial With Example https://appdividend.com/2018/12/21/angular-7-pipes-tutorial-example/ https://appdividend.com/2018/12/21/angular-7-pipes-tutorial-example/#comments Fri, 21 Dec 2018 07:01:25 +0000 http://localhost/wordpress/?p=2825 Angular Pipe Example Tutorial

Angular 7 Pipes Tutorial With Example is today’s leading topic. Angular pipes are the way to write display-value transformations that you can declare in your HTML component. Angular Pipes were earlier called filters in AngularJS and called pipes from Angular 2 onwards. The pipe takes the data as input and transforms it the desired output. If you want […]

The post Angular 7 Pipes Tutorial With Example appeared first on AppDividend.

]]>
Angular Pipe Example Tutorial

Angular 7 Pipes Tutorial With Example is today’s leading topic. Angular pipes are the way to write display-value transformations that you can declare in your HTML component. Angular Pipes were earlier called filters in AngularJS and called pipes from Angular 2 onwards. The pipe takes the data as input and transforms it the desired output.

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

Angular 7 Pipes Tutorial With Example

Angular Pipes takes the integers, strings, arrays, and dates as input separated with | to be converted in the format as required and display same in a browser. Inside the interpolation expression, we can define the pipe and use it based on the situation as there are many types of pipes we can use in an Angular application.

Built-in Angular pipes

Angular comes with the stock of pipes such as DatePipe, UpperCasePipe, LowerCasePipe, CurrentcyPipe, and PercentPipe and they are all available for use in any angular template. Angular doesn’t have the FilterPipe or an OrderByPipe. Angular doesn’t provide the pipes for filtering or sorting lists because they perform poorly and prevent aggressive minification. They both filter and order require parameters that reference object properties. Pipes are the great way to encapsulate and share a common display-value transformation.

  1. AsyncPipe
  2. CurrencyPipe
  3. DatePipe
  4. DecimalPipe
  5. JsonPipe
  6. PercentPipe
  7. LowerCasePipe
  8. UpperCasePipe
  9. SlicePipe
  10. TitleCasePipe

Example

Let us install a brand new Angular 7 project by typing the following command.

 

Angular 7 Pipes Tutorial With Example

Now, let us use the Date pipe in Angular. So write the following code inside the app.component.ts file.

// app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  birthday = new Date(1993, 8, 10);
}

Remember, the month is starting from 0. So January is 0 and so on.

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

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

<div style="text-align:center">
  <h1>
    Krunal's birthdate is {{ birthday | date }}
  </h1>

<router-outlet></router-outlet>

So, here, we have used the DatePipe to display the date property in the date format.

 

Angular 7 Pipes

Parameterizing a pipe

We can also pass a parameter to the pipe. You can write the HTML code like this to pass the parameter.

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

<h1>
    Krunal's birthdate is {{ birthday | date:"dd/MM/yyyy" }}
</h1>

Save the file, and you can see inside the browser that the page has a different date format as defined here.

Chaining pipes

We can chain pipes together in and create useful combinations. We can use the uppercase or lowercase pipe in our example.

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

<h1>
    Krunal's birthdate is {{ birthday | date | uppercase }}
</h1>

Now, your date is in uppercase letters.

Pure and impure pipes

There are two categories of pipes: 

1) pure 

2) impure

By default, the pipes in Angular are Pure. Every pipe you have seen so far has been pure like built-in pipes. You can make the pipe impure by setting the pure flag to false.

Pure pipes

Angular executes the pure pipe only when it detects the absolute change to an input value.  The pure change is either in the change to the primitive input value (String, Number, Boolean,  Symbol) or a changed object reference (Date, Array, Function, Object).

Impure pipes

Angular executes the contaminated pipe during every component change detection cycle. The impure pipe is called often, as often as every keystroke or mouse-move.

How to Create a Custom Angular Pipe?

You can write your custom pipes. Let us create new pipe inside the app folder called power.pipe.ts file.

Add the following code inside it.

// power.pipe.ts

import {Pipe, PipeTransform} from '@angular/core';
@Pipe ({
   name : 'power'
})
export class PowerPipe implements PipeTransform {
   transform(base: number, exponent: number): number {
      return Math.pow(base, exponent);
   }
}

PowerPipe is responsible for returns the base to the exponent power, that is, baseexponent.

Now, we can call this pipe inside the app.component.html file like this.

<div style="text-align:center">
  <h1>
    {{2 | power: 5}}
  </h1>
</div>
<router-outlet></router-outlet>
  • The pipe is a class that is decorated with pipe metadata.
  • An Angular pipe class implements the PipeTransform interface’s transform() method that accepts an input value followed by optional parameters and returns the transformed value. In our case, we have taken the two parameters.
  • In our example, there is one additional argument to the transform method for each parameter passed to the pipe. Our pipe has one such parameter: the exponent.
  • To tell Angular that this is the pipe, you apply the @Pipe decorator, which you import from the Angular core library.
  • The @Pipe decorator allows us to define the pipe name that you can use within the template expressions. It must be the valid JavaScript identifier.

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

The post Angular 7 Pipes Tutorial With Example appeared first on AppDividend.

]]>
https://appdividend.com/2018/12/21/angular-7-pipes-tutorial-example/feed/ 1
Angular 7 Routing and Sub Routing Tutorial With Example https://appdividend.com/2018/12/14/angular-7-routing-and-sub-routing-tutorial-with-example/ https://appdividend.com/2018/12/14/angular-7-routing-and-sub-routing-tutorial-with-example/#comments Fri, 14 Dec 2018 02:00:12 +0000 http://localhost/wordpress/?p=2540 Angular Routing Example Tutorial

Angular 7 Routing and Sub Routing Tutorial With Example is today’s leading topic. If you want to navigate to different pages in your application, but you also want the application to be an SPA (Single Page Application), with no page reloading, then your app needs routing and angular makes it very easy. Routing means navigating between the pages. […]

The post Angular 7 Routing and Sub Routing Tutorial With Example appeared first on AppDividend.

]]>
Angular Routing Example Tutorial

Angular 7 Routing and Sub Routing Tutorial With Example is today’s leading topic. If you want to navigate to different pages in your application, but you also want the application to be an SPA (Single Page Application), with no page reloading, then your app needs routing and angular makes it very easy. Routing means navigating between the pages. You have seen many websites with links that direct you to the new page. This can be achieved using routing.

We also see the sub routing or children routing for our components. That means, in our application, there is one root route and other routes are for their respective components. If we want to make our Angular application modular, then it is the best practice to assign the routes module-wise. We will take an example of how we can create root route and child routes in this angular 7 routing and sub routing tutorial with an example.

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

Angular 7 Routing and Sub Routing Tutorial

Now, the first thing is to create an Angular 7 project. Type the following command to create it. Please install or update Angular CLI, if you have not done already.

Step 1: Install Angular 7 Project

Type the following command to create it.

ng new ang7route

Remember, you need to add the app routing by saying yes to the prompt when you are creating a new project like this. Here I have allowed adding Angular routing.

 

Angular 7 Routing and Sub Routing Tutorial With Example

Now, install the bootstrap css framework.

npm install bootstrap --save

Add the Bootstrap file inside the angular.json file.

"styles": [
     "src/styles.css",
     "./node_modules/bootstrap/dist/css/bootstrap.min.css"
],

Next step is to create one header component. So type the following command.

ng g c header --spec=false

We will create a navigation bar inside that component. So, write the following code inside the header.component.html file.

<!-- header.component.html -->

<nav class="navbar navbar-expand-lg navbar-light" style="background-color: #e3f2fd;">
    <a class="navbar-brand brand-custom" href="#">Angular 7 Routing Example</a>
    <div class="collapse navbar-collapse" id="navbarText">
        <ul class="navbar-nav ml-auto">
            <li class="nav-item">
                <a class="nav-link login-custom" href="#">Students <span class="sr-only">(current)</span></a>
            </li>
            <li class="nav-item">
                <a class="nav-link register-custom" href="#">Home</a>
            </li>
        </ul>
    </div>
</nav>

Now, finally replace the app.component.html code with the following code.

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

<div>
    <app-header></app-header>    
</div>

Save the file and start the angular development server.

ng serve --open

You will see the navigation bar with three nav items.

So here, one item is Home, and one is Students.

That means, our application has one root route for home and others are sub-routes like for students module.

At the time of creating the project, we have created one routing module called app-routing.module.ts. So we will define the Root routes inside that file.

Step 2: Add Root Routes

First, create a home component by the following command.

ng g c home --spec=false

Now, add that component inside the app-routing.module.ts file.

// app-routing.component.ts

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

import { HomeComponent } from './home/home.component';

const routes: Routes = [
    {
        path: 'home',
        component: HomeComponent
    }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

So, here we have defined the root routes for our angular application. Now add the router-outlet inside the app.component.html file to display the content of the home component.

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

<div>
    <app-header></app-header>
    <div class="container">
        <router-outlet></router-outlet>
    </div>
</div>

Also, add the navigation link inside the header.component.html file.

<!-- header.component.html -->

<li class="nav-item">
     <a class="nav-link register-custom" routerLink="/home">Home</a>
</li>

Save the file and go to the browser and click the Home link. You can see that we can see the content of the home.component.html file. So, we have taken care of the Root routes. Now, it is time to create a student module and also define the sub-routes of the student module.

Step 3: Create a student module and components.

The first step is to create a module called the student. So let us create using the following command.

ng g module student

So, it will create a folder inside the app folder called the student, and inside that folder, it will create a student.module.ts file.

Next step is to create the three angular components related to student module. So let us do that.

ng g c student/student --spec=false
ng g c student/student-list --spec=false
ng g c student/student-detail --spec=false

It will create the three folders inside the src >> app >> student folder.

Now, all these four components are already imported inside the student.module.ts file.

// student.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { StudentComponent } from './student/student.component';
import { StudentListComponent } from './student-list/student-list.component';
import { StudentDetailComponent } from './student-detail/student-detail.component';

@NgModule({
  declarations: [StudentComponent, StudentListComponent, StudentDetailComponent],
  imports: [
    CommonModule
  ]
})
export class StudentModule { }

Now, we do not need to import all these components inside the app.module.ts file.

Instead, we need to import this student.module.ts file inside the app.module.ts file.

// app.module.ts

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

import { AppRoutingModule } from './app-routing.module';
import { StudentModule } from './student/student.module';

import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { HomeComponent } from './home/home.component';

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    HomeComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    StudentModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

So, all of our student components are registered to the angular application.

Step 4: Create Student route.

Now, inside the src >> app >> student folder, we can create a routing file called student-routing.module.ts and add the following code inside it.

// student-routing.module.ts

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

import { StudentComponent } from './student/student.component';
import { StudentListComponent } from './student-list/student-list.component';
import { StudentDetailComponent } from './student-detail/student-detail.component';

const routes: Routes = [
    {
        path: 'student',
        component: StudentComponent,
        children: [
            {
                path: 'list',
                component: StudentListComponent
            },
            {
                path: 'detail',
                component: StudentDetailComponent
            }
        ]
    }
];


@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class StudentRoutingModule { }

So, here we have defined the sub-routing for the student module. The main path is a  /student and its children are /student/list and /student/detail.

So that means, we have defined the subroutes for the student module. Now, the only thing remaining is to register this routing module to the student.module.ts file.

Remember, both student.module.ts, and student-routing.module.ts files are different. You can see this structure as same as our root angular project structure like app.module.ts and app-routing.module.ts.

// student.module.ts

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

import { StudentRoutingModule } from './student-routing.module';

import { StudentComponent } from './student/student.component';
import { StudentListComponent } from './student-list/student-list.component';
import { StudentDetailComponent } from './student-detail/student-detail.component';

@NgModule({
  declarations: [StudentComponent, StudentListComponent, StudentDetailComponent],
  imports: [
    CommonModule,
    StudentRoutingModule
  ]
})
export class StudentModule { }

Now, we need to display the routes. So add the following code inside the student.component.html file.

<!-- student.component.html -->

<div class="container">
    <router-outlet></router-outlet>
</div>

This router-outlet will only show the component related to the student module. So it is different from the root routing’s router-outlet which is still in the place inside the app.component.html file.

Also, now add the router link inside the header.component.html file.

<!-- header.component.html -->

<nav class="navbar navbar-expand-lg navbar-light" style="background-color: #e3f2fd;">
    <a class="navbar-brand brand-custom" href="#">Angular 7 Routing Example</a>
    <div class="collapse navbar-collapse" id="navbarText">
        <ul class="navbar-nav ml-auto">
            <li class="nav-item">
                <a class="nav-link login-custom" routerLink="/student/list">Students <span class="sr-only">(current)</span></a>
            </li>
            <li class="nav-item">
                <a class="nav-link register-custom" routerLink="/home">Home</a>
            </li>
        </ul>
    </div>
</nav>

Save the file and to the browser and navigate to the http://localhost:4200/student/list

You can see that it is rendering the correct component. Now, go to the http://localhost:4200/student/detail

It will also show the right component, and now our student module is working.

You can still go to the http://localhost:4200/home, and it will render the correct component which is HomeComponent.

This is how you can organize your Angular Project module wise with the root and children routing.

Summary of Angular Routing

  1. You added the Angular router to navigate among different components.
  2. You turned the AppComponent into a navigation shell with <a> links and a <router-outlet>.
  3. You configured the router in an AppRoutingModule.
  4. You configured the router in the StudentRoutingModule.
  5. You defined simple routes, a redirect route.
  6. You used the routerLink directive in anchor elements.

Finally, Angular 7 Routing and Sub Routing Tutorial With Example is over. Thanks for taking.

Github Code

The post Angular 7 Routing and Sub Routing Tutorial With Example appeared first on AppDividend.

]]>
https://appdividend.com/2018/12/14/angular-7-routing-and-sub-routing-tutorial-with-example/feed/ 1