Angular 5 – AppDividend https://appdividend.com Latest Code Tutorials Tue, 23 Oct 2018 09:35:08 +0000 en-US hourly 1 https://wordpress.org/?v=5.2.2 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png Angular 5 – AppDividend https://appdividend.com 32 32 Angular Unit Testing Example Tutorial From Scratch https://appdividend.com/2018/03/26/angular-unit-testing-example-tutorial/ https://appdividend.com/2018/03/26/angular-unit-testing-example-tutorial/#comments Mon, 26 Mar 2018 14:03:04 +0000 http://localhost:8888/wordpress/?p=134 Angular Unit Testing Example Tutorial From Scratch

In this example, we will see Angular Unit Testing Example Tutorial From Scratch. We will use  Angular 5 for Unit Testing. We will know how you can setup Jasmine and write unit tests for your angular components. Jasmine is the behavior-driven development framework for testing JavaScript code. Jasmine is an open source testing framework from Pivotal Labs that uses behavior-driven notation resulting in a smooth […]

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

]]>
Angular Unit Testing Example Tutorial From Scratch

In this example, we will see Angular Unit Testing Example Tutorial From Scratch. We will use  Angular 5 for Unit Testing. We will know how you can setup Jasmine and write unit tests for your angular components. Jasmine is the behavior-driven development framework for testing JavaScript code. Jasmine is an open source testing framework from Pivotal Labs that uses behavior-driven notation resulting in a smooth and improved testing experience. The Angular CLI downloads and install everything you need to test an Angular application with the Jasmine test framework. The project you create with the CLI is immediately ready to test. Just run this one CLI command.

Angular Unit Testing Example

You need to set up a dev environment before you can do anything.

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

Step 1. Set up the Development Environment.

Install the Angular CLI globally on your machine.

sudo npm install -g @angular/cli

For Windows machine, type the following command in the administrator mode.

npm install -g @angular/cli

Step 2. Create a new project.

Okay, now we need to create skeleton application by typing the following command.

ng new my-app

Now, we need to go into that project folder and start the development server.

cd my-app

ng serve

You can see our application is running on port: 4200.

The project you create with the CLI is immediately ready to test. Just run this one CLI command:

ng test

 

Angular 5 Unit Test Example

You can see one browser window is open and we can see that our test is passed.

 

Karma Tutorial Example

The test is described inside src  >>  app  >>  app.component.spec.ts file.

// app.component.ts

import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));
  it('should create the app', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));
  it(`should have as title 'app'`, async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app.title).toEqual('app');
  }));
  it('should render title in a h1 tag', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!');
  }));
});

Step 2: Write one Unit Test.

Okay, now create a component by typing the following command.

ng g c dash

It will create a dash folder inside src  >> app folder. Now add new property title inside the dash.component.ts file.

// dash.component.ts

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

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

  title = 'dash';
  constructor() { }

  ngOnInit() {
  }

}

Now, when we have created the component, an angular cli had also created the test file called dash.component.spec.ts.

// dash.component.spec.ts

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { DashComponent } from './dash.component';

describe('DashComponent', () => {
  let component: DashComponent;
  let fixture: ComponentFixture<DashComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ DashComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(DashComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

});

Next, We will write one test. So type the following code inside describe() function.

// dash.component.spec.ts

it(`should have as title 'dash'`, async(() => {
    fixture = TestBed.createComponent(DashComponent);
    component = fixture.debugElement.componentInstance;
    expect(component.title).toEqual('dash');
}));

What it will do is that first, it creates an environment to test the dash component, and then we create that component’s instance to check its properties and methods. In this example, we are just testing its property which is equal to ‘dash.’ Now, we have already started the ng test, so we can see that all of our specs are passed, at this time, a total specs is 5.

Angular Jasmine Unit Test

 

So, this is how we can write our own test.

Step 3: Run the DOM Element check spec.

Okay, next step will be to check the text of the component. Whether we are getting the same text as described in a component or not. In our case, the component is a dash. For this spec, we need to include the By() and DebugElement from the @angular/core and @angular/platform-browser package.

 So import that inside dash.component.spec.ts file.

// dash.component.spec.ts

import { DebugElement } from '@angular/core';
import { By } from '@angular/platform-browser';

Now, add the third variable inside the describe DashComponent.

// dash.component.spec.ts

let component: DashComponent;
let fixture: ComponentFixture<DashComponent>;
let de: DebugElement;

Finally, write the spec to check the text of the component.

// dash.component.spec.ts

it('should have a h1 tag of `dash works!`', () => {
    expect(de.query(By.css('p')).nativeElement.innerText).toBe('dash works!');
});

Now, our dash.component.html file looks like this by default.

<p>
  dash works!
</p>

So this test must be passed because we are checking the same text. After saving the file, we can see that we have six specs are passed. Now, change in the text like just toBe(‘dash works’). See the output, and you will see the one test is failed.

Jasmine Karma Testing Tutorial

 

We will see an advanced Unit testing the upcoming Tutorials. Our Angular Unit Testing Example is over. Thanks for taking this post.

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

]]>
https://appdividend.com/2018/03/26/angular-unit-testing-example-tutorial/feed/ 3
Angular Components Tutorial Example From Scratch https://appdividend.com/2018/01/28/angular-components-tutorial-example-scratch/ https://appdividend.com/2018/01/28/angular-components-tutorial-example-scratch/#respond Sun, 28 Jan 2018 12:38:56 +0000 http://localhost/appdividend/?p=1579 Angular Components Tutorial Example From Scratch

Angular Components Tutorial Example From Scratch is today’s leading topic. When you install the project via Angular CLI then by default, we got one component that is app component. Components are the smallest pieces in the Angular Application. We can define the Components in Typescript file. Components are just regular TypeScript class but with the Component Decorator. It […]

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

]]>
Angular Components Tutorial Example From Scratch

Angular Components Tutorial Example From Scratch is today’s leading topic. When you install the project via Angular CLI then by default, we got one component that is app component. Components are the smallest pieces in the Angular Application. We can define the Components in Typescript file. Components are just regular TypeScript class but with the Component Decorator. It differentiates standard class from the component class.

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

Angular Components Tutorial

If you analyze the app.component.ts file you will see something like this.

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

Here component is defined by a decorator @Component. It contains metadata. Angular Application reads this and identifies this class as a component class.

Component = Class + Metadata + Template

So it is a combination of above three terminologies.

// app.component.ts

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

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

In above’s example, first, we have imported a Component module from the angular core module. Then we have defined decorator and described the metadata. Metadata contains three things.

  1. selector
  2. templateUrl
  3. styleUrls

So it described as a which selector this component uses and what is the template URL and what is the Style URL. All the data described in the Metadata.

Apart from metadata, it contains typescript class. The class comprises of properties and methods. It is an essential TypeScript class. We can access its property in the template. In above’s example title is the property and we can access this property in the app.component.html file.

<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
</div>

selector

It defines as HTML tag. In above’s example, app-root is a selector, and we can use as a tag in the HTML file.

templateUrl

It represents a view of the component. We need to give the path of the HTML file. So, we can say it is the view of the MVC architecture. We can see Component as a Controller, and we can also define the Model as a Data of the component.

styleUrls

We give the path of the particular CSS file for a particular component.

New Angular Component Creation.

If are using AngularCLI then we can hit the following command in the terminal to generate a new component.

ng g c start

It will generate following files.

create src/app/start/start.component.html (24 bytes)
create src/app/start/start.component.spec.ts (621 bytes)
create src/app/start/start.component.ts (265 bytes)
create src/app/start/start.component.css (0 bytes)

Here, automatic Angular will register this component for us in the app.module.ts file. So when we create a new component, we need to register in the file. Otherwise, it will not work.

// app.module.ts

import { StartComponent } from './start/start.component';

declarations: [
    AppComponent,
    StartComponent
],

This component has its view, own css and own logic or controller file.

For more information visit its Official Documentation.

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

]]>
https://appdividend.com/2018/01/28/angular-components-tutorial-example-scratch/feed/ 0
Angular Firebase Tutorial With Example From Scratch https://appdividend.com/2018/01/26/angular-firebase-tutorial-example-scratch/ https://appdividend.com/2018/01/26/angular-firebase-tutorial-example-scratch/#comments Fri, 26 Jan 2018 13:38:14 +0000 http://localhost/appdividend/?p=1568 Angular Firebase Tutorial

Angular Firebase Tutorial With Example From Scratch is today’s leading topic. We will use Angular 5 as a frontend and Firebase as a backend database service. If you are new to Angular Framework, then please check out my other tutorials like Angular Dependency Injection Tutorial Example, Angular Services Tutorial With Example From Scratch and Angular 5 CRUD Tutorial Example From […]

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

]]>
Angular Firebase Tutorial

Angular Firebase Tutorial With Example From Scratch is today’s leading topic. We will use Angular 5 as a frontend and Firebase as a backend database service. If you are new to Angular Framework, then please check out my other tutorials like Angular Dependency Injection Tutorial ExampleAngular Services Tutorial With Example From Scratch and Angular 5 CRUD Tutorial Example From Scratch. We will build Stock Market Application where the user can insert and display the share price from the Firebase.  It is just a skeleton that demonstrates how to do a most common operation with Angular and Firebase. Firebase used a NoSQL Database.

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

Angular Firebase Tutorial

As we know, Angular uses TypeScript Language, which is a superset of Javascript. It transpiles the TypeScript code into the Javascript code with the help of webpack. We will start by installing Angular and configure the Firebase with Angular and build the Angular Firebase Project.

Step 1: Install the Angular.

You need to set up a dev environment before you can do anything. Install Node.js® and npm if they are not already on your machine.Then install the Angular CLI globally.

npm install -g @angular/cli

Step 2. Create a new project.

Type the following command. It will create the folder structure and also install the remaining dependencies.

ng new ng5firebase

Step 3: Install Angular Firebase Module.

Hit the following command in the terminal.

npm install firebase angularfire2 --save

Step 4: Add Firebase config to environment variable.

Open /src/environments/environment.ts and add your Firebase configuration:

// environment.ts

export const environment = {
  production: false,
  firebase: {
    apiKey: '<your-key>',
    authDomain: '<your-project-authdomain>',
    databaseURL: '<your-database-URL>',
    projectId: '<your-project-id>',
    storageBucket: '<your-storage-bucket>',
    messagingSenderId: '<your-messaging-sender-id>'
  }
};

Step 5: Setup @NgModule for a AngularFireModule.

Replace the following code in 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 { AngularFireModule } from 'angularfire2';
import { AngularFireDatabaseModule } from 'angularfire2/database';
import { environment } from '../environments/environment';

@NgModule({
  imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireDatabaseModule
  ],
  declarations: [ AppComponent ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

Now, we have successfully configured the Firebase with an Angular application.

Step 6: Make two components of the application.

Create one directory inside src  >>  app folder called components.

Go to the root of the folder and in the console and hit the following command.

ng g c index
ng g c create

We have created three components. Each component will do its job. Here we are establishing the single responsibility principle for every component.

It makes a separate folder inside src  >>  app directory. We need to move all these three folders inside components folder.

Also, we need to change the app.module.ts file, to write the correct path of the imported components. By default, it’s an app directory.

Step 7: Routing and Navigation.

The Angular Router enables navigation from one view to the next as users perform application tasks.

First, we need to import the routing modules inside our app.module.ts file.

Configuration

When we have created the components, it’s by default path is different and now we have moved to the components, so now its path is different. So, first, we need to change that path in app.module.ts file.

Okay, now we need to configure the routes. So make one file inside app directory called router.module.ts file.

Write the following code in it.

// router.module.ts

import { RouterModule } from '@angular/router';
import { CreateComponent } from './components/create/create.component';
import { IndexComponent } from './components/index/index.component';

export const appRoutes: Routes = [
  { path: 'create',
    component: CreateComponent
  },
  { path: 'index',
    component: IndexComponent
  }
];

We have defined one array, and inside that array, we have registered the different routes with their components. Finally, we have exported it.

Now, import this object inside app.module.ts  and register the module.

// app.module.ts

import { appRoutes } from './router.module';

imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase),
    RouterModule.forRoot(appRoutes)
],

Step 8: Define the Router outlet.

In the app.component.html file, write the following code.

<div style="text-align:center">
  <h1>
    Welcome to {{title}}!!
  </h1>
  <nav>
    <a routerLink="create" routerLinkActive="active">Add coins</a>
  </nav>
  <router-outlet></router-outlet>
</div>

Step 9: Add Bootstrap CSS.

Download the bootstrap from its original docs and paste the CSS and JS folders inside src  >>  assets folder.
In the src >>  index.html file, add the bootstrap css file.

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

Also, change the app.component.html outlook due to bootstrap classes.

<nav class="navbar navbar-default">
  <div class="container-fluid">
    <ul class="nav navbar-nav">
      <li>
        <a routerLink="create">
          Add Share
        </a>
      </li>
      <li>
        <a routerLink="index">
          Display Shares
        </a>
      </li>
    </ul>
  </div>
</nav>

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

Step 10: Make a form in the create a component file.

First, our create.component.ts file looks like this.

// create.component.ts

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

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

  title = 'Share Market';
  constructor() { }

  ngOnInit() {
  }

}

And then, we need to make the create.component.html form design.

<div class="panel panel-primary">
  <div class="panel-body">
    <form>
      <div class="form-group">
        <label class="col-md-4">Share Name</label>
        <input type="text" class="form-control" name="name"/>
      </div>
      <div class="form-group">
        <label class="col-md-4">Share Price</label>
        <input type="text" class="form-control" name="coin_price"/>
        </div>
        <div class="form-group">
          <button type="submit" class="btn btn-primary">Add</button>
        </div>
    </form>
  </div>
</div>

Now, head over to this. http://localhost:4200/create . It looks like this.

 

Angular 5 Firebase Tutorial

Step 11: Create services to send http requests.

Type the following command in your terminal.

ng g service share

Now, import the service file into the app.module.ts file.

import { ShareService } from './coin.service';

providers: [ShareService]

Now, first, we will insert the values in the Firebase database.Include the ReactiveFormsModule in the app.module.ts file.

// app.module.ts

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

imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase),
    RouterModule.forRoot(appRoutes),
    ReactiveFormsModule
  ],

Then, we are validating the forms. So first write the form HTML in the create.component.html. 

<div class="panel panel-primary">
  <div class="panel-body">
    <form [formGroup]="angForm" novalidate>
      <div class="form-group">
        <label class="col-md-4">Share Name</label>
        <input type="text" class="form-control" formControlName="name" #name />
      </div>
      <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 class="form-group">
        <label class="col-md-4">Share Price</label>
        <input type="text" class="form-control" formControlName="price" #price/>
      </div>
      <div *ngIf="angForm.controls['price'].invalid && (angForm.controls['price'].dirty || angForm.controls['price'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['price'].errors.required">
          Price is required.
        </div>
      </div>
        <div class="form-group">
          <button (click)="addShare(name.value, price.value)" [disabled]="angForm.pristine || angForm.invalid" class="btn btn-primary">Add</button>
        </div>
    </form>
  </div>
</div>

Also, we need to write the logic of validation in the create.component.ts file.

// create.component.ts

import { Component, OnInit } from '@angular/core';
import { ShareService } from '../../share.service';
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 shareservice: ShareService, private fb: FormBuilder) {
    this.createForm();
   }
  createForm() {
    this.angForm = this.fb.group({
      name: ['', Validators.required ],
      price: ['', Validators.required ]
   });
  }
  addShare(name, price) {
     const dataObj = {
      name: name,
      price: price
    };
    this.shareservice.addShare(dataObj);
  }
  ngOnInit() {
  }
}

Write the share.service.ts file to insert the data into the database.

// share.service.ts

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';

@Injectable()
export class ShareService {

  private basePath = '/shares';
  public items: any;
  public item: any;
  constructor(private db: AngularFireDatabase) { }

  addShare(data) {
  const obj = this.db.database.ref(this.basePath);
  obj.push(data);
  console.log('Success');
  }
}

If all of your database configurations are right then now you can insert the values in the Firebase. You can see on your console. If you do not know how to configure the Firebase then check out my React Firebase Tutorial

Step 12: Display the shares data in our application.

Now, go to the index.component.ts file and replace the whole file with the following code.

// index.component.ts

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { ShareService } from '../../share.service';

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

  public shares: Observable<any[]>;
  constructor(private shareservice: ShareService) { }

  ngOnInit() {
    this.shares = this.getShares('/shares');
  }
  getShares(path) {
    return this.shareservice.getShares(path);
  }
}

Our final share.service.ts file looks like this. I have coded the fetching the data from the firebase function.

// share.service.ts

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class ShareService {

  private basePath = '/shares';
  constructor(private db: AngularFireDatabase) { }

  addShare(data) {
  const obj = this.db.database.ref(this.basePath);
  obj.push(data);
  console.log('Success');
  }

  getShares(path): Observable<any[]> {
    return this.db.list(path).valueChanges();
  }
}

And finally, our view file index.component.html looks like this.

<table class="table table-striped">
  <tr>
    <th>Share Name</th>
    <th>Share Price</th>
  </tr>
  <tr *ngFor="let share of shares | async">
    <td>{{ share.name }}</td>
    <td>{{ share.price }}</td>
  </tr>
</table>

 

Firebase Angular Tutorial Example From Scratch

Fork Me On Github

That is it, Guys. Angular Firebase Tutorial With Example From Scratch is over. Thanks.

.

 

 

 

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

]]>
https://appdividend.com/2018/01/26/angular-firebase-tutorial-example-scratch/feed/ 14
Angular Animation Tutorial With Example From Scratch https://appdividend.com/2018/01/24/angular-animation-tutorial-example-scratch/ https://appdividend.com/2018/01/24/angular-animation-tutorial-example-scratch/#comments Wed, 24 Jan 2018 13:10:28 +0000 http://localhost/appdividend/?p=1558 Angular Animation Tutorial With Example From Scratch

Angular Animation Tutorial With Example From Scratch is today’s leading topic. In this Angular 5 Animation Example, we will see how we can import the angular animations module and use it in our application. Angular offers the ability to create compelling animations and activate them based on a variety of factors. You can place animations on any […]

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

]]>
Angular Animation Tutorial With Example From Scratch

Angular Animation Tutorial With Example From Scratch is today’s leading topic. In this Angular 5 Animation Example, we will see how we can import the angular animations module and use it in our application. Angular offers the ability to create compelling animations and activate them based on a variety of factors. You can place animations on any HTML element and make them occur based on lifecycles, events. One of the critical changes from Angular 4 to 5 was the fact that they moved the animation core functions from the external libraries to Angular CLI package. So we just need to import this package into an app.module.ts file.

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

Angular Animation Tutorial

First, we need to install the Angular 5 Project via Angular CLI.

Step 1:  Install the Angular CLI globally.

Hit the following command in your terminal.

npm install -g @angular/cli

Step 2. Create a new project.

Type the following command.

ng new ng5animations

Step 3: Serve the application.

Go to the project directory and launch the server.

cd my-app
ng serve --open

Step 4: Import Animations Module.

Go to the app.module.ts file and add the following code.

// app.module.ts

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

 imports: [
    BrowserModule, BrowserAnimationsModule
 ],

Step 5: Use Bootstrap CSS Framework.

Go to the Bootstrap Official Website. We will use the CDN and paste those links in our index.html file.

<!-- index.html -->

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

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
  <app-root></app-root>
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>

Step 6: Create An Animation Component.

In the src  >>  app folder, make one TypeScript file called animate.component.ts.

// animate.component.ts

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

@Component({
  selector: 'app-animate',
  template: `<div class="myblock mx-auto"></div>`,
  styles: [`
  .myblock {
    background-color: green;
    width: 300px;
    height: 250px;
    border-radius: 5px;
    margin: 5rem;
  }
  `]
})

export class AnimateComponent {}

Now, import this component into the app.module.ts file.

// app.module.ts

import { AnimateComponent } from './animate.component';

declarations: [
    AppComponent, AnimateComponent
],

Finally, include the selector into the app.component.ts file.

// app.component.ts

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

@Component({
  selector: 'app-root',
  template: `<app-animate></app-animate>`,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Angular 5 Animations Tutorial';
}

So in the browser, Green rectangle component will be there.

Angular 5 Animation Tutorial With Example From Scratch

Step 7: Create the buttons to trigger the animation.

Next thing, we need to define the proper grid in the app.component.ts file to put the buttons in the browser and trigger the animation event based on click event.

// app.component.ts

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

@Component({
  selector: 'app-root',
  template: `<div class="container">
    <div class="row">
      <div class="col-md-6">
        <div class="row">
          <div class="col-md-12 buttonanimate">
            <div class="col-md-6">
              <a (click)="animateSquare('normal')" class="btn btn-danger">Animate1</a>
            </div>
            <div class="col-md-6">
              <a (click)="animateSquare('animated')" class="btn btn-warning">Animate2</a>
            </div>
        </div>
        </div>
        <div class="col-md-3">
        </div>
      </div>
      <div class="col-md-6">
        <app-animate></app-animate>
      </div>
    </div>
  </div>`,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Angular 5 Animations Tutorial';
  nextState = 'normal';
  animateSquare(state) {
    this.nextState = state;
  }
}

Here, I have completed the code for Buttons and Square. I am explaining what is happening right now.

I have defined two buttons. When the user clicks the button, it will call the function that changes the animation state. Now, we just need to connect our changed state to the animation code to change the layout of the square.

Also, our app.component.css file looks like this.

.buttonanimate{
  margin: 5rem;
}

Step 8: Write the animation css code.

I have imported the animation functions inside this file. When the user clicks the button, this animate block will trigger a changeState and react according to it.

We have written the logic; when the button is clicked, then it will transform from either normal state to animated state or animated state to normal state.

// animate.component.ts

import { Component, Input } from '@angular/core';
import { trigger, state, style, animate, transition } from '@angular/animations';

@Component({
  selector: 'app-animate',
  template: `<div [@changeState]="currentState" class="myblock mx-auto"></div>`,
  styles: [`
  .myblock {
    background-color: green;
    width: 300px;
    height: 250px;
    border-radius: 5px;
    margin: 5rem;
  }
  `],
  animations: [
    trigger('changeState', [
      state('normal', style({
        backgroundColor: 'green',
        transform: 'scale(1)'
      })),
      state('animated', style({
        backgroundColor: 'blue',
        transform: 'scale(1.5)'
      })),
      transition('*=>normal', animate('800ms')),
      transition('*=>animated', animate('200ms'))
    ])
  ]
})

export class AnimateComponent {
  @Input() currentState;
}

Here, @Input is used to receive the property from the parent component. So it gets the state from the parent component and will change according to it.

 

Angular 4 Animation Tutorial For Beginners

Github Repository

Fork Me On Github

Finally, our Angular Animation Tutorial Example From Scratch is over.

 

 

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

]]>
https://appdividend.com/2018/01/24/angular-animation-tutorial-example-scratch/feed/ 1
Angular 5 CRUD Tutorial Example From Scratch https://appdividend.com/2018/01/21/angular-5-crud-tutorial-example-scratch/ https://appdividend.com/2018/01/21/angular-5-crud-tutorial-example-scratch/#comments Sun, 21 Jan 2018 13:58:42 +0000 http://localhost/appdividend/?p=1538 Angular 5 Crud Tutorial

Angular 5 CRUD Tutorial Example From Scratch is today’s leading topic. NodeJS is a platform nowadays because of its features and Express is a web framework build on top of Node.js. Angular CRUD Tutorial is the perfect example of  How to use Angular and Node.js together. We will use MongoDB as a database. It is sort of like MEAN Stack Application. We will cover the detailed […]

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

]]>
Angular 5 Crud Tutorial

Angular 5 CRUD Tutorial Example From Scratch is today’s leading topic. NodeJS is a platform nowadays because of its features and Express is a web framework build on top of Node.js. Angular CRUD Tutorial is the perfect example of  How to use Angular and Node.js together. We will use MongoDB as a database. It is sort of like MEAN Stack Application. We will cover the detailed tutorial about MEAN Stack in the future. Right now, just CRUD application, we will build.

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

If you want to learn Angular 6 Example then Go to the below link.

Angular 6 Tutorial With Example using Angular CLI

Prerequisites

If you are new to Angular, then please check out my these tutorials.

  1. Angular Router Tutorial Example

  2. Angular Form Validation Example Tutorial

Angular 5 CRUD Tutorial

First, we need to install the Frontend Framework. So Let’s start with the Installing the Angular Framework. Then we will set up the routing and then we will set the API endpoint to request the server and then query the database according to request and display the information according to it.

Step 1: Install Angular via CLI.

You need to set up a dev environment before you can do anything.
Install Node.js® and npm if they are not already on your machine.

 Then install the Angular CLI globally.
npm install -g @angular/cli

Step 2. Create a new project.

Type the following command. It will create the folder structure and also install the remaining dependencies.

ng new ng5crud

Step 3: Make three components of the application.

Create one directory inside src  >>  app folder called components.

Go to the root of the folder and in the console and hit the following command.

ng g c index
ng g c create
ng g c edit

We have created three components. Each component will do its job. Here we are establishing the single responsibility principle for every component.

It makes a separate folder inside src  >>  app directory. We need to move all these three folders inside components folder.

Also, we need to change the app.module.ts file, to write the correct path of the imported components. By default, it’s an app directory.

Step 4: Routing and Navigation.

The Angular Router enables navigation from one view to the next as users perform application tasks.
First, we need to import the routing modules inside our app.module.ts file.

// app.module.ts

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

imports: [
    BrowserModule, RouterModule
],

Configuration

When we have created the components, it’s by default path is different and now we have moved to the components, so now its path is different. So, first, we need to change that path in app.module.ts file.

Okay, now we need to configure the routes. So make one file inside app directory called routerConfig.ts file.

Write the following code in it.

// routerConfig.ts

import { Routes } from '@angular/router';
import { CreateComponent } from './components/create/create.component';
import { EditComponent } from './components/edit/edit.component';
import { IndexComponent } from './components/index/index.component';

export const appRoutes: Routes = [
  { path: 'create', 
    component: CreateComponent 
  },
  {
    path: 'edit/:id',
    component: EditComponent
  },
  { path: 'index',
    component: IndexComponent
  }
];

We have defined one array, and inside that array, we have registered the different routes with their components. Finally, we have exported it.

Now, import this object inside app.module.ts and register the module.

// app.module.ts

import { appRoutes } from './routerConfig';

imports: [
    BrowserModule,
    RouterModule.forRoot(appRoutes)
],

Step 5: Define the Router outlet.

In the app.component.html file, write the following code.

<div style="text-align:center">
  <h1>
    Welcome to {{title}}!!
  </h1>
  <nav>
    <a routerLink="create" routerLinkActive="active">Add coins</a>
  </nav>
  <router-outlet></router-outlet>
</div>

Also, we need to change the title attribute.

// app.component.ts

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

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

Step 6: Add Bootstrap CSS.

Download the bootstrap from its original docs and paste the CSS and JS folders inside src  >>  assets folder.

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

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

Also, change the app.component.html outlook due to bootstrap classes.

<nav class="navbar navbar-default">
  <div class="container-fluid">
    <ul class="nav navbar-nav">
      <li class="active">
        <a routerLink="create" routerLinkActive="active">
          Add coins
        </a>
      </li>    
    </ul>
  </div>
</nav>

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

Step 7: Make a form in the create a component file.

First, our create.component.ts file looks like this.

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

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

  title = 'Add Coin';
  constructor() { }

  ngOnInit() {
  }

}

And then, we need to make the create.component.html form design.

<div class="panel panel-primary">
    <div class="panel-heading">
      {{ title }}
    </div>
    <div class="panel-body">
      <form>
        <div class="form-group">
          <label class="col-md-4">Coin Name</label>
          <input type="text" class="form-control" name="coin_name"/>
        </div>
        <div class="form-group">
          <label class="col-md-4">Coin Price</label>
          <input type="text" class="form-control" name="coin_price"/>
          </div>
          <div class="form-group">
            <button type="submit" class="btn btn-primary">Add</button>
          </div>
      </form>
    </div>
  </div>

Now, head over to this. http://localhost:4200/create . It looks like this.

Angular CRUD Tutorial

Step 8: Configure HttpClientModule.

Go to the app.module.ts file. Include the HttpClientModule in it.

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

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

Step 9: Create services to send http requests.

Type the following command in your terminal.

ng g service coin

It will create the following classes.

  1. coin.service.ts
  2. coin.service.spec.ts

Now, import the service file into the app.module.ts file.

import { CoinService } from './coin.service';

providers: [CoinService]

Step 10: Configure Node.js MongoDB backend.

Next step, would be to create Node.js and Express backend to store the data. Create one file in the project root called server.js

Now, we need to install the express framework and other dependencies via NPM, so let us do it first.

npm install --save express body-parser cors mongoose nodemon

Switch to newly created server.js file and enter the following code into it.

// server.js

var express = require('express'),
      path = require('path'),
      bodyParser = require('body-parser'),
      cors = require('cors'),
      mongoose = require('mongoose');

      const app = express();
      var port = process.env.PORT || 4000;

      var server = app.listen(function(){
        console.log('Listening on port ' + port);
      });

Next thing is we need to create the MongoDB database and connect it with our express application.

Note: You need to have installed MongoDB database on your server or local otherwise first you need to download it and start the MongoDB server.

Create one config folder inside project root. In that create one file called DB.js.

// DB.js

module.exports = {
   DB: 'mongodb://localhost:27017/angularcrud'
};

Import this file into our server.js file and use mongoose to set up a database connection with MongoDB. You need to copy the whole server.js file; I am about to show so that nothing will left and lead us to error.

// server.js

const express = require('express'),
      path = require('path'),
      bodyParser = require('body-parser'),
      cors = require('cors'),
      mongoose = require('mongoose'),
      config = require('./config/DB');

      mongoose.Promise = global.Promise;
      mongoose.connect(config.DB).then(
          () => {console.log('Database is connected') },
          err => { console.log('Can not connect to the database'+ err)}
        );

      const app = express();
      app.use(bodyParser.json());
      app.use(cors());
      const port = process.env.PORT || 4000;

       const server = app.listen(port, function(){
         console.log('Listening on port ' + port);
       });

Step 11: Create Express routes for our application.

Now, we need to create two folders in a root called expressRoutes and models.

In models folder, create one model called Coin.js.

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// Define collection and schema for Items
var Coin = new Schema({
  name: {
    type: String
  },
  price: {
    type: Number
  }
},{
    collection: 'coins'
});

module.exports = mongoose.model('Coin', Coin);

In the expressRouter folder, create one file called coinRoutes.js.

// coinRoutes.js

var express = require('express');
var app = express();
var coinRoutes = express.Router();

// Require Item model in our routes module
var Coin = require('../models/Coin');

// Defined store route
coinRoutes.route('/add').post(function (req, res) {
  var coin = new Coin(req.body);
   coin.save()
    .then(item => {
    res.status(200).json({'coin': 'Coin added successfully'});
    })
    .catch(err => {
    res.status(400).send("unable to save to database");
    });
});

// Defined get data(index or listing) route
coinRoutes.route('/').get(function (req, res) {
   Coin.find(function (err, coins){
    if(err){
      console.log(err);
    }
    else {
      res.json(coins);
    }
  });
});

// Defined edit route
coinRoutes.route('/edit/:id').get(function (req, res) {
  var id = req.params.id;
  Coin.findById(id, function (err, coin){
      res.json(coin);
  });
});

//  Defined update route
coinRoutes.route('/update/:id').post(function (req, res) {
   Coin.findById(req.params.id, function(err, coin) {
    if (!coin)
      return next(new Error('Could not load Document'));
    else {
      coin.name = req.body.name;
      coin.price = req.body.price;

      coin.save().then(coin => {
          res.json('Update complete');
      })
      .catch(err => {
            res.status(400).send("unable to update the database");
      });
    }
  });
});

// Defined delete | remove | destroy route
coinRoutes.route('/delete/:id').get(function (req, res) {
   Coin.findByIdAndRemove({_id: req.params.id}, function(err, coin){
        if(err) res.json(err);
        else res.json('Successfully removed');
    });
});

module.exports = coinRoutes;

Here, I have defined all the routes related to CRUD application.
This file will be included in our server.js file.

// server.js

coinRoutes = require('./expressRoutes/coinRoutes');

app.use('/coins', coinRoutes);

Step 12: Insert the value in the MongoDB.

From the front end side, we need to set up HttpClientModule and fire up the HTTP Post call to the NodeJS server.

// server.js

const express = require('express'),
      path = require('path'),
      bodyParser = require('body-parser'),
      cors = require('cors'),
      mongoose = require('mongoose'),
      config = require('./config/DB'),
      coinRoutes = require('./expressRoutes/coinRoutes');

mongoose.Promise = global.Promise;
mongoose.connect(config.DB).then(
    () => {console.log('Database is connected') },
    err => { console.log('Can not connect to the database'+ err)}
  );

const app = express();
app.use(bodyParser.json());
app.use(cors());
const port = process.env.PORT || 4000;

app.use('/coins', coinRoutes);

const server = app.listen(port, function(){
  console.log('Listening on port ' + port);
});

We need to include the ReactiveFormsModule in the app.module.ts file.

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

import { AppComponent } from './app.component';
import { IndexComponent } from './components/index/index.component';
import { CreateComponent } from './components/create/create.component';
import { EditComponent } from './components/edit/edit.component';
import { appRoutes } from './routerConfig';

import { CoinService } from './coin.service';

@NgModule({
  declarations: [
    AppComponent,
    IndexComponent,
    CreateComponent,
    EditComponent
  ],
  imports: [
    BrowserModule, RouterModule.forRoot(appRoutes), HttpClientModule, ReactiveFormsModule
  ],
  providers: [CoinService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Then, we are validating the forms. So first write the form HTML in the create.component.html. 

<div class="panel panel-primary">
    <div class="panel-heading">
      {{ title }}
    </div>
    <div class="panel-body">
      <form [formGroup]="angForm" novalidate>
        <div class="form-group">
          <label class="col-md-4">Coin Name</label>
          <input type="text" class="form-control" formControlName="name" #name />
        </div>
        <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 class="form-group">
          <label class="col-md-4">Coin Price</label>
          <input type="text" class="form-control" formControlName="price" #price/>
        </div>
        <div *ngIf="angForm.controls['price'].invalid && (angForm.controls['price'].dirty || angForm.controls['price'].touched)" class="alert alert-danger">
          <div *ngIf="angForm.controls['price'].errors.required">
            Price is required.
          </div>
        </div>
          <div class="form-group">
            <button (click)="addCoin(name.value, price.value)" [disabled]="angForm.pristine || angForm.invalid" class="btn btn-primary">Add</button>
          </div>
      </form>
    </div>
  </div>

Also, we need to write the logic of validation in the create.component.ts file.

// create.component.ts

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

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

  title = 'Add Coin';
  angForm: FormGroup;
  constructor(private coinservice: CoinService, private fb: FormBuilder) {
    this.createForm();
   }
  createForm() {
    this.angForm = this.fb.group({
      name: ['', Validators.required ],
      price: ['', Validators.required ]
   });
  }
  addCoin(name, price) {
      this.coinservice.addCoin(name, price);
  }
  ngOnInit() {
  }
}

 

MEAN Stack Tutorial With Example From Scratch

Write the coin.service.ts file to insert the data into the database.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';

@Injectable()
export class CoinService {

  constructor(private http: HttpClient) { }

  addCoin(name, price) {
    const uri = 'http://localhost:4000/coins/add';
    const obj = {
      name: name,
      price: price
    };
    this.http.post(uri, obj)
        .subscribe(res => console.log('Done'));
  }
}

Start the node.js server by typing: node server. If all the database configuration is right then, you can see the data is inserting into the database.

Step 13: Display the data to the frontend.

In the index.component.html file, write the following code.

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

  <tbody>
      <tr *ngFor="let coin of coins">
          <td>{{ coin.name }}</td>
          <td>{{ coin.price }}</td>
          <td><a [routerLink]="['/edit', coin._id]" class="btn btn-primary">Edit</a></td>
          <td><a routerLink="" class="btn btn-danger">Delete</a></td>
      </tr>
  </tbody>
</table>

Also, you need to update the index.component.ts file and call the service functions to make an http get request.

import { CoinService } from './../../coin.service';
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

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

  coins: any;

  constructor(private http: HttpClient, private service: CoinService) {}

  ngOnInit() {
    this.getCoins();
  }

  getCoins() {
    this.service.getCoins().subscribe(res => {
      this.coins = res;
    });
  }
}

Write the coin.service.ts file to make an http get request.

import { Injectable } from '@angular/core';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
export class CoinService {

  result: any;
  constructor(private http: HttpClient) {}

  addCoin(name, price) {
    const uri = 'http://localhost:4000/coins/add';
    const obj = {
      name: name,
      price: price
    };
    this
      .http
      .post(uri, obj)
      .subscribe(res =>
          console.log('Done'));
  }

  getCoins() {
    const uri = 'http://localhost:4000/coins';
    return this
            .http
            .get(uri)
            .map(res => {
              return res;
            });
  }

  editCoin(id) {
    const uri = 'http://localhost:4000/coins/edit/' + id;
    return this
            .http
            .get(uri)
            .map(res => {
              return res;
            });
  }
}

Now, move over to http://localhost:4200/index

It will display the data. Now, we need to add the actions to Edit and Delete.

Step 14: Edit and Delete the Coins.

Now, first, we need to fetch the data from the database and display in the edit form. So first, edit form looks like this. Write the following code in the edit.component.html file.

<div class="panel panel-primary">
  <div class="panel-heading">
    {{ title }}
  </div>
  <div class="panel-body">
    <form [formGroup]="angForm" novalidate>
      <div class="form-group">
        <label class="col-md-4">Coin Name</label>
        <input type="text" class="form-control" formControlName="name" #name [(ngModel)] = "coin.name"/>
      </div>
      <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 class="form-group">
        <label class="col-md-4">Coin Price</label>
        <input type="text" class="form-control" formControlName="price" #price [(ngModel)] = "coin.price" />
      </div>
      <div *ngIf="angForm.controls['price'].invalid && (angForm.controls['price'].dirty || angForm.controls['price'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['price'].errors.required">
          Price is required.
        </div>
      </div>
        <div class="form-group">
          <button (click)="updateCoin(name.value, price.value)" [disabled]="angForm.pristine || angForm.invalid" class="btn btn-primary">Update</button>
        </div>
    </form>
  </div>
</div>

Okay, next step is code the edit.component.ts file.

// edit.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { CoinService } from './../../coin.service';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';

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

  coin: any;
  angForm: FormGroup;
  title = 'Edit Coin';
  constructor(private route: ActivatedRoute, private router: Router, private service: CoinService, private fb: FormBuilder) {
    this.createForm();
   }

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

  updateCoin(name, price) {
    this.route.params.subscribe(params => {
    this.service.updateCoin(name, price, params['id']);
    this.router.navigate(['index']);
  });
}

  ngOnInit() {
    this.route.params.subscribe(params => {
      this.coin = this.service.editCoin(params['id']).subscribe(res => {
        this.coin = res;
      });
    });
  }
}

Now, also write the code into the coin.service.ts file.

import { Injectable } from '@angular/core';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
export class CoinService {

  result: any;
  constructor(private http: HttpClient) {}

  addCoin(name, price) {
    const uri = 'http://localhost:4000/coins/add';
    const obj = {
      name: name,
      price: price
    };
    this
      .http
      .post(uri, obj)
      .subscribe(res =>
          console.log('Done'));
  }

  getCoins() {
    const uri = 'http://localhost:4000/coins';
    return this
            .http
            .get(uri)
            .map(res => {
              return res;
            });
  }

  editCoin(id) {
    const uri = 'http://localhost:4000/coins/edit/' + id;
    return this
            .http
            .get(uri)
            .map(res => {
              return res;
            });
  }

  updateCoin(name, price, id) {
    const uri = 'http://localhost:4000/coins/update/' + id;

    const obj = {
      name: name,
      price: price
    };
    this
      .http
      .post(uri, obj)
      .subscribe(res => console.log('Done'));
  }
}

I have already written edit and update service to make an API call. So till now, Create, Read, Update is complete. Now, take a look at Delete.

Now, I am coding the whole index.component.html file.

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

  <tbody>
      <tr *ngFor="let coin of coins">
          <td>{{ coin.name }}</td>
          <td>{{ coin.price }}</td>
          <td><a [routerLink]="['/edit', coin._id]" class="btn btn-primary">Edit</a></td>
          <td><button (click)="deleteCoin(coin._id)"  class="btn btn-danger">Delete</button></td>
      </tr>
  </tbody>
</table>

Also, write the deleteCoin() function edit.component.ts file.

deleteCoin(id) {
    this.service.deleteCoin(id).subscribe(res => {
      console.log('Deleted');
    });
}

Finally, whole coin.service.ts file looks like this.

import { Injectable } from '@angular/core';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
export class CoinService {

  result: any;
  constructor(private http: HttpClient) {}

  addCoin(name, price) {
    const uri = 'http://localhost:4000/coins/add';
    const obj = {
      name: name,
      price: price
    };
    this
      .http
      .post(uri, obj)
      .subscribe(res =>
          console.log('Done'));
  }

  getCoins() {
    const uri = 'http://localhost:4000/coins';
    return this
            .http
            .get(uri)
            .map(res => {
              return res;
            });
  }

  editCoin(id) {
    const uri = 'http://localhost:4000/coins/edit/' + id;
    return this
            .http
            .get(uri)
            .map(res => {
              return res;
            });
  }

  updateCoin(name, price, id) {
    const uri = 'http://localhost:4000/coins/update/' + id;

    const obj = {
      name: name,
      price: price
    };
    this
      .http
      .post(uri, obj)
      .subscribe(res => console.log('Done'));
  }

  deleteCoin(id) {
    const uri = 'http://localhost:4000/coins/delete/' + id;

        return this
            .http
            .get(uri)
            .map(res => {
              return res;
            });
  }
}

In this tutorial, I have not done any code that does not prevent the page refresh; You need to refresh the page to see the changes. So I just want you to know that this is how you can write the CRUD application.

Fork Me On Github

Finally, Angular 5 CRUD Tutorial Example From Scratch is over.

 

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

]]>
https://appdividend.com/2018/01/21/angular-5-crud-tutorial-example-scratch/feed/ 59
Angular Services Tutorial With Example From Scratch https://appdividend.com/2018/01/20/angular-services-tutorial-example-scratch/ https://appdividend.com/2018/01/20/angular-services-tutorial-example-scratch/#comments Sat, 20 Jan 2018 09:54:27 +0000 http://localhost/appdividend/?p=1528 Angular Services Tutorial With Example From Scratch

Angular Services Tutorial With Example From Scratch is today’s leading topic. We are using Angular 5 for this tutorial. Components should not fetch or save data directly, and they indeed shouldn’t knowingly present fake data. They should focus on representing data and delegate data access to a service. Services are a great way to share information among classes that do not […]

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

]]>
Angular Services Tutorial With Example From Scratch

Angular Services Tutorial With Example From Scratch is today’s leading topic. We are using Angular 5 for this tutorial. Components should not fetch or save data directly, and they indeed shouldn’t knowingly present fake data. They should focus on representing data and delegate data access to a service. Services are a great way to share information among classes that do not know each otherWhen we are developing an Angular app, we will most likely run into a scenario in which we need to use the same code across multiple components. In that case, Services will help us to get rid of this problem. We can share the services code among various components.

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

If you are new to Angular then please check out my these tutorials.

  1. Angular Router Tutorial Example

  2. Angular Form Validation Example Tutorial

  3. Angular Dependency Injection Tutorial Example

Angular Services Tutorial

We should not violate some general programming principles like Single Responsibility Of A Class. In this case, Components use to display and present the data. Services use to fetch the data from the API. Let us get started our Angular 5 Services Tutorial.

Step 1: Install Angular via CLI.

You need to set up a dev environment before you can do anything.

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

 Then install the Angular CLI globally.
npm install -g @angular/cli

Step 2. Create a new project.

Type the following command.

ng new ngservices

Step 3: Serve the application.

Go to the project directory and launch the server.

cd my-app
ng serve --open

Step 4: Create Service class.

To create a service, at the console, type the following command in your root of the folder.

ng g service crypto

It will create the following files.

  1. crypto.service.ts
  2. crypto.service.spec.ts

Now, import the service file into the app.module.ts file.

import { CryptoService } from './crypto.service';

@NgModule({
  providers: [CryptoService], 
})

Now, we need to add some code to the crypto.service.ts file. This file contains the data that we need to consume. So this is service file. In the Live project, this file will hit the GET or POST request to the server and insert or fetch the data. So this file provides services from frontend to backend.

// items.service.ts

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

@Injectable()
export class CryptoService {

  coins= [
    {id: 1, name: 'BTC'},
    {id: 2, name: 'XRP'}
  ];

  constructor() { }

  getMyItems()
  {
    return this.coins;
  }

}

Step 5: Use services into the component.

So your app.component.ts file looks like this.

// app.component.ts

import { Component } from '@angular/core';
import { CryptoService } from './crypto.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  coins = [];
  constructor(private cryptoservice: CryptoService)
  {
    this.coins = cryptoservice.getMyItems();
  }
}

Also, we need to update the HTML as well.

<table>
  <tr>
    <th>ID</th>
    <th>Name</th>
  </tr>
  <tr *ngFor="let coin of coins">
    <td>{{coin.id}}</td>
    <td>{{coin.name}}</td>
  </tr> 
</table>

Finally, you can see in the browser: http://localhost:4200

You can see the data is displaying the table format.

In a real-world scenario, data is fetching from the Backend API. In this case, we have taken simple static Array.

Finally, our Angular Services Tutorial With Example From Scratch is over.

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

]]>
https://appdividend.com/2018/01/20/angular-services-tutorial-example-scratch/feed/ 3
Angular 5 Material Tutorial From Scratch https://appdividend.com/2018/01/18/angular-5-material-tutorial-scratch/ https://appdividend.com/2018/01/18/angular-5-material-tutorial-scratch/#comments Fri, 19 Jan 2018 03:53:51 +0000 http://localhost/appdividend/?p=1520 Angular 5 Material Tutorial With Example From Scratch

Angular 5 Material Tutorial From Scratch is today’s leading topic. Technically, It’s an Angular, but I have defined a particular version because there are some changes with every new Angular release. Since AngularJS to Angular, there are so many changes even the whole framework is changed. So bear with me and let us get started to […]

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

]]>
Angular 5 Material Tutorial With Example From Scratch

Angular 5 Material Tutorial From Scratch is today’s leading topic. Technically, It’s an Angular, but I have defined a particular version because there are some changes with every new Angular release. Since AngularJS to Angular, there are so many changes even the whole framework is changed. So bear with me and let us get started to this Angular Material Tutorial With Example From Scratch.

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

Angular 5 Material Tutorial

First, we need to install the Angular CLI globally in our system. You can find the full documentation on its original website We need to install it globally, so type the following command.

npm install -g @angular/cli

Step 1: Create a project.

Go to your cmd and type the following command.

ng new ng5material

It will create a new project. All the boilerplate will be included in this project.

Step 2: Install Angular Material and Angular CDK.

Type the following command to install the dependencies.

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

Step 3: Install Animations.

To work with Angular Material, we need to install animations module to work our design correctly.

npm install --save @angular/animations

We need to import the angular animation module into app.module.ts file.

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

imports: [
    BrowserModule, BrowserAnimationsModule
],

Now, we are creating our module, which is responsible for all of our Angular Material Components.

So create one file inside src  >>  app folder and create one file called ngmaterial.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {  MatButtonModule } from '@angular/material';

@NgModule({
  imports: [MatButtonModule],
  exports: [MatButtonModule]
})
export class MaterialAppModule { }

Okay, so we have included the MatButtonModule in our app. Now, we need to register this custom MaterialAppModule in our 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 { MaterialAppModule } from './ngmaterial.module';

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


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

Including a theme is required to apply all of the core and theme styles to your application.

To get started with a pre-built theme, include one of Angular Material’s prebuilt themes globally in your application. If you’re using the Angular CLI, you can add this to your style.css

// style.css

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

Also, It is good to include the material icons in our application. So in the index.html file, include the following css file.

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

Some components (mat-slide-togglemat-slidermatTooltip) rely on HammerJS for gestures. To get the full feature-set of these elements, HammerJS must be loaded into the application.

You can add HammerJS to your application via npm, a CDN (such as the Google CDN), or served directly from your app.

To install via npm, use the following command:

npm install --save hammerjs

After installing, import it into your app’s entry point (e.g. src/main.ts).

// main.ts

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

import 'hammerjs';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.log(err));

Okay, now everything is included correctly. Just write one essential Material component inside the app.component.html file.

// app.component.html

<button mat-button>Material Button</button>

Get rid of all the previous HTML and start the angular development server by the following command.

ng serve

Now, go the browser port: 4200 and URL will be: http://localhost:4200

You can see there is one button and if you click it, then some animation will be displayed as well. So finally our Material Design is included in our Angular 5 Application.

Step 6: Include other components.

You can find more about its official documentation.
We includeToolbar in our application.

<mat-toolbar>  
  <mat-toolbar-row>
    <span>First Row</span>
  </mat-toolbar-row>

  <mat-toolbar-row>
    <span>Second Row</span>
  </mat-toolbar-row>
</mat-toolbar>

Also, include in our ngmaterial.module.ts file.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {  MatButtonModule } from '@angular/material';
import { MatToolbarModule } from '@angular/material/toolbar';

@NgModule({
  imports: [MatButtonModule, MatToolbarModule],
  exports: [MatButtonModule, MatToolbarModule]
})
export class MaterialAppModule { }

This is how you can integrate different material components.

We will see the advanced components in the next tutorial. So here the basic introduction of Angular 5 Material Tutorial With Example From Scratch is over.

Fork Me On Github

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

]]>
https://appdividend.com/2018/01/18/angular-5-material-tutorial-scratch/feed/ 4