How to add dynamic text in ng-model name

Is it possible to add dynamic text in the&nbsp;<code>ng-model</code>&nbsp;name?

Is it possible to add dynamic text in the ng-model name?

data js

self.Map = [{ Id: 0, Name: 'Map1' }, { Id: 1, Name: 'Map2' }, { Id: 2, Name: 'Map3' }]

html

<div ng-repeat="option in mainCtrl.Map">
    <div style="text-align:left;" class="col-md-6">
        {{option.Name}} Map
    </div>
    <div style="text-align:right;" class="col-md-6">
        <input type="text" id="Is{{option.Name}}" name="Is{{option.Name}}" ng-model="mainCtrl.Is{{option.Name}}"/>
    </div>
</div>

desired output

ng-model="mainCtrl.IsMap1"


Frontend vs Backend vs Fullstack Web Development - What should you learn?

Frontend vs Backend vs Fullstack Web Development - What should you learn?

Frontend vs Backend vs Fullstack Web Development - What should you learn? In Web Development, there's Frontend (JS, HTML, CSS), Backend (PHP, Node.js, DBs, ...) and Fullstack (Everything?) Development. What's the best one?

In Web Development, there's Frontend (JS, HTML, CSS), Backend (PHP, Node.js, DBs, ...) and Fullstack (Everything?) Development. What's the best one?
Limited Offer! Join the Full Node.js Course at 90% off: http://bit.ly/2O0oN6c
Exclusive Discount also available for these courses:

  • React.js: http://bit.ly/36Qm6ww
  • Angular: http://bit.ly/2X0yLZc
  • Vue.js: http://bit.ly/32xDUcj
  • MongoDB: http://bit.ly/34MsB1y
  • CSS: http://bit.ly/2NXtbCZ

How to Validate Phone Number with Javascript

How to Validate Phone Number with Javascript

The validating phone number is an important point while validating an HTML form. In this post we have discussed how to validate a phone number (in different format) using JavaScript

The validating phone number is an important point while validating an HTML form. In this page we have discussed how to validate a phone number (in different format) using JavaScript :

At first, we validate a phone number of 10 digits with no comma, no spaces, no punctuation and there will be no + sign in front the number. Simply the validation will remove all non-digits and permit only phone numbers with 10 digits. Here is the function.

function phonenumber(inputtxt)
{
  var phoneno = /^\d{10}$/;
  if((inputtxt.value.match(phoneno))
        {
      return true;
        }
      else
        {
        alert("message");
        return false;
        }
}

Flowchart:

Flowchart : JavaScript phone validation-1

To valid a phone number like
XXX-XXX-XXXX
XXX.XXX.XXXX
XXX XXX XXXX
use the following code.

function phonenumber(inputtxt)
{
  var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
  if((inputtxt.value.match(phoneno))
        {
      return true;
        }
      else
        {
        alert("message");
        return false;
        }
}

Flowchart:

Flowchart : JavaScript - phone validation-2

If you want to use a + sign before the number in the following way
+XX-XXXX-XXXX
+XX.XXXX.XXXX
+XX XXXX XXXX
use the following code.


function phonenumber(inputtxt)
{
  var phoneno = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
  if((inputtxt.value.match(phoneno))
        {
      return true;
        }
      else
        {
        alert("message");
        return false;
        }
}

Flowchart:

Flowchart : JavaScript - phone validation-3

Following code blocks contain actual codes for the said validations. We have kept the CSS code part common for all the validations.

CSS Code

 li {list-style-type: none;
font-size: 16pt;
}
.mail {
margin: auto;
padding-top: 10px;
padding-bottom: 10px;
width: 400px;
background : #D8F1F8;
border: 1px soild silver;
}
.mail h2 {
margin-left: 38px;
}
input {
font-size: 20pt;
}
input:focus, textarea:focus{
background-color: lightyellow;
}
input submit {
font-size: 12pt;
}
.rq {
color: #FF0000;
font-size: 10pt;
}

Validate a 10 digit phone number

At first we validate a phone number of 10 digit. For example 1234567890, 0999990011, 8888855555 etc.

HTML Code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript form validation - checking non-empty</title>
<link rel='stylesheet' href='form-style.css' type='text/css' />      
</head><body onload='document.form1.text1.focus()'>
<div class="mail">
<h2>Input an Phone No.[xxxxxxxxxx] and Submit</h2>
<form name="form1" action="#">
<ul>
<li><input type='text' name='text1'/></li>
<li>&nbsp;</li>
<li class="submit"><input type="submit" name="submit" value="Submit" onclick="phonenumber(document.form1.text1)"/></li>
<li>&nbsp;</li>
</ul>
</form>
</div>
<script src="phoneno-all-numeric-validation.js"></script>
</body>
</html>

JavaScript Code

function phonenumber(inputtxt)
{
  var phoneno = /^\d{10}$/;
  if(inputtxt.value.match(phoneno))
  {
      return true;
  }
  else
  {
     alert("Not a valid Phone Number");
     return false;
  }
  }

Flowchart:

Flowchart : JavaScript - phone validation 10 digit

Validate North American phone numbers

Now, let's see how to validate a phone number, either in 222-055-9034, 321.789.4512 or 123 256 4587 formats.

HTML Code

<!DOCTYPE html><html lang="en"><head>
<meta charset="utf-8">
<title>JavaScript form validation - checking non-empty</title>
<link rel='stylesheet' href='form-style.css' type='text/css' />      
</head>
<body onload='document.form1.text1.focus()'>
<div class="mail">
<h2>Input an Phone No.[xxx-xxx-xxxx, xxx.xxx.xxxx, xxx xxx xxxx] and Submit</h2>
<form name="form1" action="#"> 
<ul>
<li><input type='text' name='text1'/></li>
<li>&nbsp;</li>
<li class="submit"><input type="submit" name="submit" value="Submit" onclick="phonenumber(document.form1.text1)"/></li>
<li>&nbsp;</li>
</ul>
</form>
</div>
<script src="phoneno-international-format.js"></script>
</body>
</html>

JavaScript Code

function phonenumber(inputtxt)
{
  var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
  if(inputtxt.value.match(phoneno))
     {
	   return true;      
	 }
   else
     {
	   alert("Not a valid Phone Number");
	   return false;
     }
}

Flowchart:

Flowchart : JavaScript - phone validation North America

Validate an international phone number with country code

Now, let's see how to validate a phone number with country code, either in +24-0455-9034, +21.3789.4512 or +23 1256 4587 format.

HTML Code

<!DOCTYPE html><html lang="en"><head>
<meta charset="utf-8">
<title>JavaScript form validation - checking non-empty</title>
<link rel='stylesheet' href='form-style.css' type='text/css' />
</head>

<body onload='document.form1.text1.focus()'>
<div class="mail">
<h2>Input an Phone No.[+xx-xxxx-xxxx, +xx.xxxx.xxxx, +xx xxxx xxxx] and Submit</h2>
<form name="form1" action="#"> 
<ul>
<li><input type='text' name='text1'/></li>
<li>&nbsp;</li>
<li class="submit"><input type="submit" name="submit" value="Submit" onclick="phonenumber(document.form1.text1)"/></li>
<li>&nbsp;</li>
</ul>
</form>
</div>
<script src="phoneno-+international-format.js"></script>
</body>
</html>

JavaScript Code

function phonenumber(inputtxt)
{
  var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
  if(inputtxt.value.match(phoneno))
     {
	   return true;
	 }
   else
     {
	   alert("Not a valid Phone Number");
	   return false;
     }
}

Thank you for visiting and reading !

Angular 7 CRUD With Node.JS API

Angular 7 CRUD With Node.JS API

In this article, we are going to create a very basic Angular 7 CRUD (Create, Read, Update and Delete) application with Node.JS REST API endpoints. With the help of our REST API, we will work on our MongoDB database, and perform various operations on Products collection.

In this article, we are going to create a very basic Angular 7 CRUD (Create, Read, Update and Delete) application with Node.JS REST API endpoints. With the help of our REST API, we will work on our MongoDB database, and perform various operations on Products collection.

Angular 7 Prerequisites

Before start writing the Angular 7 app, please make sure that, you have latest version of:

  • Node.JS and NPM installed on your system
  • Angular 7 CLI installed on your system
MongoDB Backend Overview

Let me introduce you about the MongoDB Document structure. We have Products collection in our database, and this Products collection have multiple documents related to various products.

This is the screenshot of our MongoDB Products collection.

And this is the screenshot of each Product document.

{
    "_id": {
        "$oid": "5c3162ed7829481868c3afe9"
    },
    "title": "HP",
    "description": "15 inch HP Laptop",
    "price": 1500,
    "company": "HP",
    "createdAt": {
        "$date": "2019-01-06T02:07:41.477Z"
    },
    "updatedAt": {
        "$date": "2019-01-06T02:07:41.477Z"
    },
    "__v": 0
}

Node.JS Rest API Endpoints

You can get all details of Node.JS Rest API in the above link, which I shared on the top of this post. Let me share again, which endpoints we have for our application. These are the list of our API endpoints.

// Create a new Product
    app.post('/products', products.create);

    // Retrieve all Products
    app.get('/products', products.findAll);

    // Retrieve a single Product with productId
    app.get('/products/:productId', products.findOne);

    // Update a Note with productId
    app.put('/products/:productId', products.update);

    // Delete a Note with productId
    app.delete('/products/:productId', products.delete);

Creating Angular 7 Project

Let’s start with our Angular 7 app. Using above Node.JS API endpoints, we are going to perform CRUD operation. This will be the screen of our Angular app.

Create your angular app using the ng new  command in your terminal.

1. Creating Model Class In Angular

After creating our app, let’s first create our Product Model class as per our database Product Document properties.

ProductModel.ts

export class ProductModel {
    _id: string;
    title: String;
    description: String;
    price: Number;
    company: String;
}

2. Creating Service In Angular

Let’s create our Product Service class, which will interact with our Node.JS endpoints for all product related operations.

product.service.ts

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

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

  constructor(private http: HttpClient) { }

  baseurl: string = "http://localhost:3000/";

  getAllProducts(){
    return this.http.get<ProductModel[]>(this.baseurl + 'Products');
  }

  getProductById(id: string){
    return this.http.get<ProductModel>(this.baseurl + 'Products' + '/' + id);
  }

  addProduct(product: ProductModel){
    return this.http.post(this.baseurl + 'Products', product);
  }

  deleteProduct(id: string){
    return this.http.delete(this.baseurl + 'Products' + '/' + id);
  }

  updateProduct(product: ProductModel){
    return this.http.put(this.baseurl + 'Products' + '/' + product._id, product);
  }
}

We have imported HttpClient and ProductModel in our service class.

This is our service url endpoint.

baseurl: string = “http://localhost:3000/”;
In this class, we have different methods. These are:

  • Node.JS and NPM installed on your system
  • Angular 7 CLI installed on your system

Import Product Service in app.module

Now, after creating the product service, we have to import this in our app.module.ts file. Let’s do it now.

app.module.ts

Add this line on the top of app.module.ts file.

baseurl: string = “http://localhost:3000/”;
And this ProductService in Providers[] array.
baseurl: string = “http://localhost:3000/”;## 3. Creating Component For Listing All Products

First of all, we are going to fetch all the products in our database. Create list-products component, and add this to our routing module. This component will fetch all the products from the database and display it in tabular form. Add routing details of this component in our route file.

app-routing.module.ts

Import ListProductsComponent in our routing file.

baseurl: string = “http://localhost:3000/”;
And, add this in routes constant.
baseurl: string = “http://localhost:3000/”;
This is our list-products component html file.

list-products.component.html

<div class="container col-md-12"> 
    <div>
        <button (click)="addProduct()" class="btn btn-info">Add Product</button>
      </div> 
  <h2>All Products</h2>  
  <div class="table-responsive table-container">  
    <table class="table table-dark table-hover table-striped">  
      <thead class="thead-light">  
        <tr>  
          <th>Title</th>  
          <th>Description</th> 
          <th>Price($)</th> 
          <th>Company</th>
          <th>Action</th> 
        </tr>  
      </thead>  
      <tbody>  
        <tr *ngFor="let product of products"> 
           
          <td>{{product.title}}</td>  
          <td>{{product.description}}</td>
          <td>{{product.price | currency : "USD" : true}}</td> 
          <td>{{product.company}}</td> 
           
          <td>  
            <button (click)="deleteProduct(product)" class="btn btn-info"> Delete</button>  
            <button (click)="updateProduct(product)" style="margin-left: 20px;" class="btn btn-info"> Edit</button>  
          </td>  
        </tr>  
      </tbody>  
    </table>  
  </div> 
   
</div> 

list-products.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from "@angular/router";
import { ProductModel } from '../ProductModel';
import { ProductService } from '../product.service';

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

  products: ProductModel[];

  constructor(private productService: ProductService, private router: Router) { }

  ngOnInit() {
    this.getAllProducts();
  }

  getAllProducts(): void {
    this.productService.getAllProducts().subscribe(data=>{
      this.products = data;
    });
  };

  addProduct(): void {
    this.router.navigate(['add-product']);
  }

  deleteProduct(product: ProductModel){
    
    this.productService.deleteProduct(product._id).subscribe(data=>{
      console.log(data);
      this.getAllProducts();
    });
  }

  updateProduct(product: ProductModel){
    localStorage.removeItem("productId");
    localStorage.setItem("productId", product._id);
    this.router.navigate(['edit-product']);
  }

}

To get the list of all products, we have created getAllProducts() function, and call it in ngOnInit().

4. Creating Component For Adding Product

This component will be used to add a product in our database. Add routing details of this component in our route file.

app-routing.module.ts

Add this line on the top of app-routing.module.ts file.

baseurl: string = “http://localhost:3000/”;
And, add this in routes constant.
baseurl: string = “http://localhost:3000/”;
This is our add-product component file.

add-product.component.html

<div class="col-md-3">
    <h2 class="text-center">Add Product</h2>
    <form [formGroup]="addForm" (ngSubmit)="onSubmit()">
      <div class="form-group">
        <label>Title:</label>
        <input type="text" formControlName="title" placeholder="Title" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.title.errors }">
        <div *ngIf="submitted && f.title.errors">
          <div *ngIf="f.title.errors.required">Title is required</div>
        </div>
      </div>
  
      <div class="form-group">
        <label>Description:</label>
        <input type="text" formControlName="description" placeholder="Description" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.description.errors }">
        <div *ngIf="submitted && f.description.errors">
          <div *ngIf="f.description.errors.required">Description is required</div>
        </div>
      </div>
  
      <div class="form-group">
        <label>Price ($):</label>
        <input type="text" formControlName="price" placeholder="Price" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.price.errors }">
        <div *ngIf="submitted && f.price.errors">
          <div *ngIf="f.price.errors.required">Price is required</div>
        </div>
      </div>

      <div class="form-group">
          <label>Company:</label>
          <input type="text" formControlName="company" placeholder="Company" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.company.errors }">
          <div *ngIf="submitted && f.company.errors">
            <div *ngIf="f.company.errors.required">Company is required</div>
          </div>
      </div>
  
      <button type="submit"  class="btn btn-info">Save</button>
    </form>
  </div>

add-product.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from "@angular/forms";
import { ProductService } from '../product.service';
import { first } from "rxjs/operators";
import { Router } from "@angular/router";

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

  constructor(private formBuilder: FormBuilder, private router: Router, private productService: ProductService) { }

  addForm: FormGroup;
  submitted = false;

  ngOnInit() {
    this.addForm = this.formBuilder.group({
      _id: [],
      title: ['', Validators.required],
      description: ['', Validators.required],
      price: ['', Validators.required],
      company: ['', Validators.required]
    });
  }

  onSubmit(){
    this.submitted = true;
    
    if(this.addForm.valid){
      this.productService.addProduct(this.addForm.value)
      .subscribe( data => {
        console.log(data);
        this.router.navigate(['']);
      });
    }
  }

  // get the form short name to access the form fields
  get f() { return this.addForm.controls; }

}

In this component class, we have used Validators to check whether all required fields are filled or not. When user click on Add Product button on Product List page, user will be navigating to the Add Product page.

                   ![](https://i1.wp.com/www.zeptobook.com/wp-content/uploads/2019/01/Add-Product.png?fit=635%2C1024&ssl=1)

In the above pic, if you try to save without filing all the fields, it will red highlight the textbook and let you not to save the product. So, fill all the fields and save the new product. As soon as your product is saved, you will be redirecting again to the all products page with newly product added.

Also, notice the following code in list-products.component.html file. We have (click) event on the Add Product button, and calling the addProduct() method of list-products.component.ts class. In this method, we are simply navigating to our route add-product, and opening the add-product component page.

addProduct(): void {
    this.router.navigate(['add-product']);
  }

5. Delete Product

In order to delete any product, we don’t need to create any component. For each product in grid on list-products.component.html component, we have Delete button attached to it. There is an deleteProduct(product) method on (click) event of this Delete button. deleteProduct(product) method is defined in list-products.component.ts file.

deleteProduct(product: ProductModel){
    this.productService.deleteProduct(product._id).subscribe(data=>{
      console.log(data);
      this.getAllProducts();
    });
  }

After deleting the product, we are fetching all the products again by calling this.getAllProducts() method.

6. Creating Component For Updating Product

In order to update any product, we are going to create another component. Create component edit-product in your app. Add creating your component, we have to define the route as well in your app. Open the app-routing.module.tsfile and import this component there.

app-routing.module.ts

baseurl: string = “http://localhost:3000/”;
Add the route in routes constant.
baseurl: string = “http://localhost:3000/”;#### edit-product.component.html

<div class="col-md-3">
  <h2 class="text-center">Edit Product</h2>
  <form [formGroup]="editForm" (ngSubmit)="onSubmit()">
    <div class="form-group">
      <label>Title:</label>
      <input type="text" formControlName="title" placeholder="Title" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.title.errors }">
      <div *ngIf="submitted && f.title.errors">
        <div *ngIf="f.title.errors.required">Title is required</div>
      </div>
    </div>

    <div class="form-group">
      <label>Description:</label>
      <input type="text" formControlName="description" placeholder="Description" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.description.errors }">
      <div *ngIf="submitted && f.description.errors">
        <div *ngIf="f.description.errors.required">Description is required</div>
      </div>
    </div>

    <div class="form-group">
      <label>Price ($):</label>
      <input type="text" formControlName="price" placeholder="Price" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.price.errors }">
      <div *ngIf="submitted && f.price.errors">
        <div *ngIf="f.price.errors.required">Price is required</div>
      </div>
    </div>

    <div class="form-group">
        <label>Company:</label>
        <input type="text" formControlName="company" placeholder="Company" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.company.errors }">
        <div *ngIf="submitted && f.company.errors">
          <div *ngIf="f.company.errors.required">Company is required</div>
        </div>
    </div>

    <button type="submit"  class="btn btn-info">Update</button>
  </form>
</div>

Our edit-product component html file is similar to add-product component html file. So, you can simply copy paste the same html here.

edit-product.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from "@angular/forms";
import { ProductService } from '../product.service';
import { first } from "rxjs/operators";
import { Router } from "@angular/router";
import { ProductModel } from '../ProductModel';

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

  product: ProductModel;
  editForm: FormGroup;
  submitted = false;

  constructor(private formBuilder: FormBuilder, private router: Router, private productService: ProductService) { }

  ngOnInit() {
    let productId = localStorage.getItem("productId");
    if(!productId){
      alert("Something wrong!");
      this.router.navigate(['']);
      return;
    }

    this.editForm = this.formBuilder.group({
      _id: [],
      title: ['', Validators.required],
      description: ['', Validators.required],
      price: ['', Validators.required],
      company: ['', Validators.required]
    });

    this.productService.getProductById(productId).subscribe(data=>{
      console.log(data);
      this.editForm.patchValue(data); //Don't use editForm.setValue() as it will throw console error
    });
  }

  // get the form short name to access the form fields
  get f() { return this.editForm.controls; }

  onSubmit(){
    this.submitted = true;
    
    if(this.editForm.valid){
      this.productService.updateProduct(this.editForm.value)
      .subscribe( data => {
        console.log(data);
        this.router.navigate(['']);
      });
    }
  }

}

Here, we are using localStorage.getItem() to get the productId, which was stored in our list-product.component.ts file using localStorage.setItem(). So, let’s first get the productId first from localStorage() in ngOnInit() method. See below code, how we are setting productId in localStorage(). After that, we are navigating to our edit component page.

list-product.component.ts

updateProduct(product: ProductModel){
    localStorage.removeItem("productId");
    localStorage.setItem("productId", product._id);
    this.router.navigate(['edit-product']);
  }

After retrieving the productId from localStorage, we are going to get the product using this productId in ngOnInit() function.

edit-product.component.ts

this.productService.getProductById(productId).subscribe(data=>{
      console.log(data);
      this.editForm.patchValue(data); //Don't use editForm.setValue() as it will throw console error
    });

On successful, we are setting the form values with the response data using patchValue() method.

                                                ![](https://i2.wp.com/www.zeptobook.com/wp-content/uploads/2019/01/Edit-Product.png?resize=387%2C504&ssl=1)

Update the values in the form and click on Update button. It will call the onSubmit() function of edit-product.component.ts class file. After updating the values in database, it will be redirected to product listing component page.

So, we have done with our CRUD operation on our product model. Let me show you complete app-routing and app.module files.

Angular 7 Routing: app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
import { ListProductsComponent } from './list-products/list-products.component';
import { AddProductComponent } from './add-product/add-product.component';
import { EditProductComponent } from './edit-product/edit-product.component';

const routes: Routes = [
  { path: 'add-product', component: AddProductComponent },
  { path: 'edit-product', component: EditProductComponent},
  { path: '', component: ListProductsComponent, pathMatch: 'full' }
];

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

Angular 7 Module: app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { ReactiveFormsModule } from "@angular/forms"; 

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ProductService } from './product.service';
import { ListProductsComponent } from './list-products/list-products.component';
import { AddProductComponent } from './add-product/add-product.component';
import { EditProductComponent } from './edit-product/edit-product.component';

@NgModule({
  declarations: [
    AppComponent,
    ListProductsComponent,
    AddProductComponent,
    EditProductComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    ReactiveFormsModule
  ],
  providers: [ProductService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Install Bootstrap and FontAwesome in Angular 7

Use this npm command to install the Bootstrap and FontAwesome in your project.

baseurl: string = “http://localhost:3000/”;## Importing the Bootstrap and FontAwesome

After installation, you can add these css files in your styles.css file.

/* You can add global styles to this file, and also import other style files */
@import "~bootstrap/dist/css/bootstrap.css";
@import "~font-awesome/css/font-awesome.css";

Angular 7 Project Structure

This will be our app structure.

Download

You can download all the project files from GitHub.

Download Project Files

Summary

In this blog, we learned about how to perform CRUD operation on our MongoDB database using Node.Js Api. I also shared the project files on Github, from where you can view and download it.

By : Adesh

Angular 7 Tutorial - Learn Angular 7 by Example

Angular 7 Tutorial - Learn Angular 7 by Example

Watch or read this full crash course on learning Angular 7, tutorial is perfectly suited towards a beginner with no prior Angular experience.

Watch or read this full crash course on learning Angular 7, tutorial is perfectly suited towards a beginner with no prior Angular experience.

Ever since the release of Angular 2, I have created a full course for each new iteration. Today is no different, as Angular 7 just released!

With this beginner’s crash course, I make the assumption that you have never worked with Angular before. Therefore, this tutorial is perfectly suited towards a beginner with no prior Angular experience. The only thing you should be familiar with is HTML, CSS and JavaScript.

In this course, you’re going to discover just how powerful Angular 7 is when it comes to creating frontend web apps. Let’s get started!

If you prefer watching a video…

Be sure to Subscribe to the Official Coursetro Youtube Channel for more videos.

Installation

You’re first going to need to install the Angular CLI (Command Line Interface) tool, which helps you start new Angular 7 projects as well as assist you during development. In order to install the Angular CLI, you will need Nodejs. Make sure you install this with the default options and reload your command line or console after doing so.

In your command line, type:

> npm install -g @angular/cli

Once complete, you can now access the CLI by simply starting any commands with ng.

Hop into whichever folder you want to store your projects, and run the following command to install a new Angular 7 project:

> ng new ng7-pre

It’s going to present you with a couple questions before beginning:

? Would you like to add Angular routing? Yes
? Which stylesheet format would you like to use? SCSS   [ http://sass-lang.com   ]

It will take a minute or two and once completed, you can now hop into the new project folder by typing:

> cd ng7

Open up this project in your preferred code editor (I use Visual Studio Code, and you can launch it automatically by typing code . in the current folder), and then run this command to run a development server using the Angular CLI:

> ng serve -o

-o is for open, this flag will open your default browser at http://localhost:4200. Tip: You can type ng to get a list of all available commands, and ng [command] --help to discover all their flags.

Awesome! If all went smooth, you should be presented with the standard landing page template for your new Angular 7 project:

Angular 7 Components

The most basic building block of your Angular 7 application (and this is a concept that’s not new) is the component. A component consists of three primary elements:

  • The HTML template
  • The logic
  • The styling (CSS, Sass, Stylus, etc…)

When we use the Angular CLI to start a new project, it generates a single component, which is found in /src/app/:

/app.component.html
/app.component.scss
/app.component.ts

While we have three files here that represent the three elements above, the .ts (TypeScript) is the heart of the component. Let’s take a look at that file:

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

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


Here, because this is a component, we’re importing Component from the @angular/core library, and then it defines what’s called a @Component decorator, which provides configuration options for that particular component.

As you can see, it’s referencing the location of the HTML template file and the CSS file with the templateUrl property and the styleUrls property.

The logic of the component resides in the class at the bottom. As you can see, the CLI starter template simply defines a single property called title.

Let’s use the Angular CLI to create our own components that we’ll need going forward. In the console, issue the following commands:

> ng generate component nav
// output

> ng g c about
// output

> ng g c contact
// output

> ng g c home
// output

Notice we first use the full syntax to generate a component, and then we use a shorthand syntax, which makes life a little bit easier. The commands do the same thing: generate components.

When we generate components this way, it will create a new folder in the /src/ folder based on the name we gave it, along with the respective template, CSS, .ts and .spec (for testing) files.

Angular 7 Templating

You may have noticed that one of the components we generated was called nav. Let’s implement a header bar with a navigation in our app!

The first step is to visit the app.component.html file and specify the following contents:

<app-nav></app-nav>

<section>
  <router-outlet></router-outlet>
</section>

So, we’ve removed a bunch of templating and placed in , what does this do and where does it come from?

Well, if you visit /src/app/nav/nav.component.ts you will see that in the component decorator, there’s a selector property bound to the value of app-nav. When you reference the selector of a given component in the form of a custom HTML element, it will nest that component inside of the component it’s that’s referencing it.

If you save the file you just updated, you will see in the browser we have a simple, nav works! And that’s because the nav.component.html file consists of a simple paragraph stating as much.

At this point, let’s specify the following HTML to create a simple navigation:

<header>
  <div class="container">
    <a routerLink="/" class="logo">apptitle</a>
    <nav>
      <ul>
        <li><a routerLink="/">Home</a></li>
        <li><a routerLink="/about">About</a></li>
        <li><a routerLink="/contact">Contact us</a></li>
      </ul>
    </nav>
  </div>
</header>

The only thing that might look a little strange is routerLink. This is an Angular 7 specific attribute that allows you to direct the browser to different routed components. The standard href element will not work.

While we’re here on the subject of templating, what if we wanted to display properties that are coming from our component? We use what’s called interpolation.

Make the following adjustment to our template:

<!-- From: -->
<a routerLink="/">myapp</a>

<!-- To: -->
<a routerLink="/">{{ appTitle }}</a>


Interpolation is executed by wrapping the name of a property that’s defined in the component between {{ }}.

Let’s define that property in nav.component.ts:

export class NavComponent implements OnInit {

  appTitle: string = 'myapp';
  // OR (either will work)
  appTitle = 'myapp';

  constructor() { }

  ngOnInit() {
  }

}

You can use the TypeScript way of defining properties or standard JavaScript. Save the file and you will see myapp is back in the template.

There’s a lot more to templating, but we will touch on those topics as we continue. For now, let’s apply style to our header.

First, let’s visit the global stylesheet by opening /src/styles.scss and define the following rulesets:

@import url('https://fonts.googleapis.com/css?family=Montserrat:400,700');

body, html {
    height: 100%;
    margin: 0 auto;
}

body {
    font-family: 'Montserrat';
    font-size: 18px;
}

a {
    text-decoration: none;
}

.container {
    width: 80%;
    margin: 0 auto;
    padding: 1.3em;
    display: grid;
    grid-template-columns: 30% auto;

    a {
        color: white;
    }
}

section {
    width: 80%;
    margin: 0 auto;
    padding: 2em;
}

Visit nav/component.scss and paste the following contents:

header {
    background: #7700FF;

    .logo {
        font-weight: bold;
    }

    nav {
        justify-self: right;

        ul {
            list-style-type: none;
            margin: 0; padding: 0;

            li {
                float: left;

                a {
                    padding: 1.5em;
                    text-transform: uppercase;
                    font-size: .8em;

                    &:hover {
                        background: #8E2BFF;
                    }
                }
            }
        }
    }
}

If you save and refresh, this should be the result in the browser:

Awesome!

Angular 7 Routing

Now that we have a navigation, let’s make our little app actually navigation between our components as needed.

Open up /src/app/app-routing.module.ts and specify the following contents:

// Other imports removed for brevity

import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { ContactComponent } from './contact/contact.component';

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: 'contact', component: ContactComponent },
];

// Other code removed for brevity

As we can see here, we’re defining importing our components and defining an object for each route inside of the routes constant. These route objects also accept other properties, which allow you to define URL parameters, but because our app is simple, we won’t be doing any of that.

Save this file and try clicking on the links above. You will see that each of the respective component’s HTML templating shows up in the  defined in app.component.html.

This is what the result should look like in the browser at this point:

You now know enough about Angular 7 to create a very simple website with routing! But let’s learn more than that.

Angular 7 Event Binding

In the next several sections, we’re going to use our /src/app/home component as a playground of sorts to learn features specific to Angular 7.

One of the most used forms of event binding is the click event. You often need to make your app respond when a user clicks something, so let’s do that!

Visit the /src/app/home/home.component.html template file and specify the following:

<h1>Home</h1>

<button (click)="firstClick()">Click me</button>

You define an event binding by wrapping the event between (), and calling a method. You define the method in the home.component.ts file as such:

export class HomeComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  firstClick() {
    console.log('clicked');
  }

}

Save it, get out the browser console (CTRL+SHIFT+i) and click on the button. The output should show clicked. Great!

You can experiment with the other event types by replacing (click) with the names below:

(focus)="myMethod()"
(blur)="myMethod()" 
(submit)="myMethod()"  
(scroll)="myMethod()"

(cut)="myMethod()"
(copy)="myMethod()"
(paste)="myMethod()"

(keydown)="myMethod()"
(keypress)="myMethod()"
(keyup)="myMethod()"

(mouseenter)="myMethod()"
(mousedown)="myMethod()"
(mouseup)="myMethod()"

(click)="myMethod()"
(dblclick)="myMethod()"

(drag)="myMethod()"
(dragover)="myMethod()"
(drop)="myMethod()"

Angular 7 Class & Style Binding

Sometimes you may need to change the appearance of your UI from your component logic. There are two ways to do this, through class and style binding.

There are a lot of different methods you can use to control class binding, so we won’t cover them all. But I will cover some of the most common use cases.

Let’s say that you want to control whether or not a CSS class is applied to a given element. Update the h1 element in home.component.html to the following:

<h1 [class.gray]="h1Style">Home</h1>

Here, we’re saying that the CSS class of .gray should only be attached to the h1 element if the property h1Style results to true. Let’s define that in the home.component.ts file:

  h1Style: boolean = false;

  constructor() { }

  ngOnInit() {
  }

  firstClick() {
    this.h1Style = true;
  }

Let’s also define the .gray class in this component’s scss file:

.gray {
    color: gray;
}

Save it, and you can now click on the click me button to change the color of the Home title.

What if you wanted to control multiple classes on a given element? You can use ngClass. Modify the home component’s template file to the following:

<h1 [ngClass]="{
  'gray': h1Style,
  'large': !h1Style
}">Home</h1>

Then, add the large ruleset to the .scss file:

.large {
    font-size: 4em;
}

Now give it a shot in the browser. Home will appear large, but shrink down to the regular size when you click the button. Great!

You can also control appearance by changing the styles directly from within the template. Modify the template as such:

<h1 [style.color]="h1Style ? 'gray': 'black'">Home</h1>

Refresh and give this a shot by clicking the button.

Like ngClass() there’s also an ngStyle() that works the same way:

<h1 [ngStyle]="{
  'color': h1Style ? 'gray' : 'black',
  'font-size': !h1Style ? '1em' : '4em'
}">Home</h1>

Give this a go! Awesome!

Angular 7 Services

Services in Angular 7 allow you to define code that’s accessible and reusable throughout multiple components. A common use case for services is when you need to communicate with a backend of some sort to send and receive data.

> ng generate service data

Open up the new service file /src/app/data.service.ts and let’s create the following method:

// Other code removed for brevity

export class DataService {

  constructor() { }

  firstClick() {
    return console.log('clicked');
  }
}

To use this in a component, visit /src/app/home/home.component.ts and update the code to the following:

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

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

  constructor(private data: DataService) { }

  ngOnInit() {
  }

  firstClick() {
    this.data.firstClick();
  }

}


There are 3 things happening here:

  • The HTML template
  • The logic
  • The styling (CSS, Sass, Stylus, etc…)

If you try this, you will see that it works as clicked will be printed to the console. Awesome! This means that you now know how to create methods that are accessible from any component in your Angular 7 app.

Angular 7 HTTP Client

Angular comes with its own HTTP library that we will use to communicate with a fake API to grab some data and display it on our home template. This will take place within the data.service file that we generated with the CLI.

In order to gain access to the HTTP client library, we have to visit the /src/app/app.module.ts file and make a couple changes. Up until this point, we haven’t touched this file, but the CLI has been modifying it based on the generate commands we’ve issued to it.

Add the following to the imports section at the top:

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

Next, add it to the imports array:

  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,    // <-- Right here
  ],

Now we can use it in our /src/app/data.service.ts file:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';  // Import it up here

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

  constructor(private http: HttpClient) { }

  getUsers() {
    return this.http.get('https://reqres.in/api/users')
  }
}


reqres.in is a free public API that we can use to grab data.

Open up our home.component.ts file and modify the following:

export class HomeComponent implements OnInit {

  users: Object;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.getUsers().subscribe(data => {
        this.users = data
        console.log(this.users);
      }
    );
  }

}

The first thing you might notice is that we’re placing the code inside of the ngOnInit() function, which is a lifecycle hook for Angular. Any code placed in here will run when the component is loaded.

We’re defining a users property, and then we’re calling the .getUsers() method and subscribing to it. Once the data is received, we’re binding it to our users object and also console.logging it.

Give it a try in the browser and you will see the console shows an object that’s returned. Let’s display it on our home template!

Open up home.component.html and specify the following:

<h1>Users</h1>

<ul *ngIf="users">
  <li *ngFor="let user of users.data">
    <img [src]="user.avatar">
    <p>{{ user.first_name }} {{ user.last_name }}</p>
  </li>
</ul>

Great! Let’s specify some CSS to make this look better in home.component.scss:

ul {
    list-style-type: none;
    margin: 0;padding: 0;

    li {
        background: rgb(238, 238, 238);
        padding: 2em;
        border-radius: 4px;
        margin-bottom: 7px;
        display: grid;
        grid-template-columns: 60px auto;

        p {
            font-weight: bold;
            margin-left: 20px;
        }

        img {
            border-radius: 50%;
            width: 100%;
        }
    }
}

View the result in the browser:

Awesome!

Angular 7 Forms

If you recall, we generated a component called contact. Let’s create a contact form so that you can learn how to use forms in Angular 7.

Angular 7 provides you with two different approaches to dealing with forms: template driven and reactive forms. I’m not going to go into the differences between these two approaches, but reactive forms generally provide you with more control andform validation can be unit tested as opposed to template driven forms.

To get started, we have to visit the app.module.ts file and import the Reactive Forms Module:

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

// other code
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    ReactiveFormsModule  // <- Add here
  ],

Next, visit the contact.component.ts file and specify the following

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

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

  messageForm: FormGroup;
  submitted = false;
  success = false;

  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.messageForm = this.formBuilder.group({
      name: ['', Validators.required],
      message: ['', Validators.required]
    });
  }

  onSubmit() {
    this.submitted = true;

    if (this.messageForm.invalid) {
        return;
    }

    this.success = true;
}

}


First, we’re importing FormBuilder, FormGroup, Validators from @angular/forms.

Then we’re setting a few boolean properties that will help us determine when the form has been submitted and if it validation is successful.

Then we’re creating an instance of the formBuilder in the constructor. We then use this form building to construct our form properties in the ngOnInit() lifecycle hook.

We have two properties, name and message.

Then we created an onSubmit() method that will be called when the user submits the form. This is typically where you would call upon a method in the service to communicate with a mail service of sorts.

Next, visit contact.component.html:

<h1>Contact us</h1>

<form [formGroup]="messageForm" (ngSubmit)="onSubmit()">

    <h5 *ngIf="success">Your form is valid!</h5>

    <label>
      Name:
      <input type="text" formControlName="name">
      <div *ngIf="submitted && messageForm.controls.name.errors" class="error">
        <div *ngIf="messageForm.controls.name.errors.required">Your name is required</div>
      </div>
    </label>

    <label>
      Message:
      <textarea formControlName="message"></textarea>
      <div *ngIf="submitted && messageForm.controls.message.errors" class="error">
        <div *ngIf="messageForm.controls.message.errors.required">A message is required</div>
      </div>
    </label>

    <input type="submit" value="Send message" class="cta">

  </form>

  <div *ngIf="submitted" class="results">
    <strong>Name:</strong> 
    <span>{{ messageForm.controls.name.value }}</span>

    <strong>Message:</strong> 
    <span>{{ messageForm.controls.message.value }}</span>
  </div>


Baked in here is a full form with validation. It also prints out the form values beneath it when the form has been submitted.

Let’s update the css for the component to make it look decent:

label {
    display: block;

    input, textarea {
        display: block;
        width: 50%;
        margin-bottom: 20px;
        padding: 1em;
    }

    .error {
        margin-top: -20px;
        background: yellow;
        padding: .5em;
        display: inline-block;
        font-size: .9em;
        margin-bottom: 20px;
    }
}

.cta {
    background: #7700FF;
    border: none;
    color: white;

    text-transform: uppercase;
    border-radius: 4px;
    padding: 1em;
    cursor: pointer;
    font-family: 'Montserrat';
}

.results {
    margin-top: 50px;

    strong {
        display: block;
    }
    span {
        margin-bottom: 20px;
        display: block;
    }
}

Save it, and the result in the browser should look like this!

Awesome!

Conclusion

As you can see, Angular 7 is quite powerful but we’ve only just scratched the surface. If you’re a beginner, I recommend trying to create a really simple project using what you’ve learned so far and then take it from there.

Learn More

Angular 7 (formerly Angular 2) - The Complete Guide

Learn and Understand AngularJS

Angular Crash Course for Busy Developers

The Complete Angular Course: Beginner to Advanced

Angular (Angular 2+) & NodeJS - The MEAN Stack Guide

Become a JavaScript developer - Learn (React, Node,Angular)

Angular (Full App) with Angular Material, Angularfire & NgRx

The Web Developer Bootcamp

How to export Angular page content to PDF with Kendo UI

How to export Angular page content to PDF with Kendo UI

In this tutorial, learn how to easily export pages with HTML content within your Angular application. This should be a complex task, but thanks to a Kendo UI component it is easy

If you've found yourself looking for an easy solution to smoothly export the HTML content from your Angular application to a PDF, then this is the appropriate post for you. We may need to export HTML content to PDF for several reasons, ranging from sharing it with others without necessarily accessing the internet to saving it just for documentation purposes.

Building a solution for a component like this could be time-consuming if you are building all by yourself. In this post, I will show you how to easily achieve this by leveraging the PDF export component provided by Kendo UI.

We will build an Angular application with some dummy content and add a Kendo UI button to export the content directly to PDF as shown here:

Install Angular CLI

Before creating an Angular application, you need to first install the Angular CLI if it doesn’t already exist on your machine. Open up a terminal and run the following command for that purpose:

npm install -g @angular/cli 

This will add the Angular CLI globally on your machine.

Creating Angular Application

You can now proceed to create a new app for the purpose of this post by running the command below to generate an application with the name kendo-angular-export-pdf:

ng new kendo-angular-export-pdf

Once the installation process is complete, change directory into the newly created project as shown below and start the application:

// change directory
cd kendo-angular-export-pdf
   
// start the application
ng serve

You may experience an error with the message below in your console:

ERROR in node_modules/rxjs/internal/types.d.ts(81,44): error TS1005: ';' expected.
node_modules/rxjs/internal/types.d.ts(81,74): error TS1005: ';' expected.
node_modules/rxjs/internal/types.d.ts(81,77): error TS1109: Expression expected.

This is a known issue on GitHub and it’s due to lack of compatibility between the current version of TypeScript on your machine and rxjs. The quick way to fix this is to delete the node_modules folder. Now, open the package.json file and within the dependencies object, edit the rxjs by removing ^ :

 "dependencies": {
   ...
   "rxjs": "6.0.0", // remove the `^`
   "zone.js": "^0.8.26"
 },

Save the file and run the npm install command again. Once the installation process is complete, you can now proceed to start the application with ng serve.

This will compile your application and start the development server. To view the default page of this Angular application, navigate to http://localhost:4200 from your favorite browser and you will see this:

Add PDF Export Component from Kendo UI

Next, we’ll need to add the PDF export component before we start using it in our application. To achieve that, we’ll use the ng add command to require and install the package as shown here:

ng add @progress/kendo-angular-pdf-export

This will import and add both PDFExportModule and BrowserAnimationsModule to the app.module.ts file:

// ./src/app/app/module.ts
   
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { PDFExportModule } from '@progress/kendo-angular-pdf-export';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
   
   
@NgModule({
 declarations: [
   AppComponent
 ],
 imports: [
   BrowserModule,
   PDFExportModule,
   BrowserAnimationsModule
 ],
 providers: [],
 bootstrap: [AppComponent]
})
export class AppModule { }
Use the Kendo PDF Export Component

After installing the PDF export package, you can now proceed to export content within our Angular application to PDF by placing it within the <kendo-pdf-export> component. Open ./src/app/app.component.html and replace its content with:

// ./src/app/app.component.html
   
<div class="pageWrapper">
 <div class="content">
   <kendo-pdf-export #pdf>
     <div class="size-a4">
       <p> Build Better JavaScript Apps Faster The ultimate collection of JavaScript UI components with libraries for jQuery,
         Angular, React, and Vue. Quickly build eye-catching and high-performance responsive web applications—regardless
         of your JavaScript framework choice.
       </p>
       <p> Build Better JavaScript Apps Faster The ultimate collection of JavaScript UI components with libraries for jQuery,
         Angular, React, and Vue. Quickly build eye-catching and high-performance responsive web applications—regardless
         of your JavaScript framework choice.
       </p>
     </div>
   </kendo-pdf-export>
   
   <div>
     <button kendo-button (click)="pdf.saveAs('demo-content.pdf')">
       Export As PDF
     </button>
   </div>
 </div>
</div>

Here, we have added dummy content and wrapped it with the <kendo-pdf-export></kendo-pdf-export> component. Next we added a button and attached a click event to it. Once the button is clicked, we called the saveAs() method in order to save the generated file. The file will be saved as the name passed as an argument to the saveAs() method.

Finally, to give the page some default styling, add the following content to ./src/app/app.component.css file:

// ./src/app/app.component.css
   
.pageWrapper {
 margin-top: 50px;
}
button {
   padding: 15px;
}
kendo-pdf-export {
 font-family: "DejaVu Sans", "Arial", sans-serif;
 font-size: 16px;
}
.content {
 width: 800px;
 margin: 0 auto;
 line-height: 20px;
}

Now proceed to start the application again by running ng serve from the terminal within the application’s directory. Once

the application is built and served on http://localhost:4200 you will see this:

The content displayed here is from our Angular application. To test the HTML content export functionality, click on the Kendo button with the text Export As PDF. Now open the downloaded PDF file:

Cool, right? This is the content of our page exported to PDF without much hassle. But with a close look at the PDF file, you will agree with me that something isn’t right. The content doesn’t look properly organized. We’ll change that by adding a little bit of margin in the next section.

Add Paper Size and Margin

The Kendo PDF export component API makes a provision for us to easily customize and specify the paper size of the PDF document. At the moment, it is set to the default auto which means that the paper size is determined by the content.

Let’s replace the content of ./src/app/app.component.html with:

// ./src/app/app.component.html
   
<div class="pageWrapper">
 <div class="content">
   <kendo-pdf-export #pdf paperSize="A4" margin="2cm">
     <div class="size-a4">
       <p> Build Better JavaScript Apps Faster The ultimate collection of JavaScript UI components with libraries for jQuery,
         Angular, React, and Vue. Quickly build eye-catching and high-performance responsive web applications—regardless
         of your JavaScript framework choice.
       </p>
       <p> Build Better JavaScript Apps Faster The ultimate collection of JavaScript UI components with libraries for jQuery,
         Angular, React, and Vue. Quickly build eye-catching and high-performance responsive web applications—regardless
         of your JavaScript framework choice.
       </p>
     </div>
   </kendo-pdf-export>
   
   <div>
     <button kendo-button (click)="pdf.saveAs('demo-content.pdf')">
       Export As PDF
     </button>
   </div>
 </div>
</div>

We have added two data attributes to the <kendo-pdf-export>, which are:

  • paperSize: We set this to A4.
  • margin: We set this to 2cm.

Check the page again and click on the Export As PDF button. Now proceed to open your downloaded PDF file and you will notice that it looks much better as shown below:

Conclusion

The Kendo PDF export component as shown here is a solution for exporting and handling HTML content to PDF. This comes in handy whenever you need to quickly save a page as a PDF document from your Angular application.

We have barely scratched the surface here, because there is so much more functionality provided by the Kendo UI team when exporting HTML content to PDF. Feel free to explore the API by checking the link here for more details.

Hopefully you have learned a lot from this post. Check the source code here on GitHub.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about Angular

Angular 8 (formerly Angular 2) - The Complete Guide

Angular & NodeJS - The MEAN Stack Guide

The Complete Node.js Developer Course (3rd Edition)

The Web Developer Bootcamp

Best 50 Angular Interview Questions for Frontend Developers in 2019

How to build a CRUD Web App with Angular 8.0

React vs Angular: An In-depth Comparison

React vs Angular vs Vue.js by Example

Microfrontends — Connecting JavaScript frameworks together (React, Angular, Vue etc)

Building CRUD Mobile App using Ionic 4, Angular 8

How to Build Mobile Apps with Angular, Ionic 4, and Spring Boot

Ionic 4 & Angular Tutorial For Beginners - Crash Course