Getting Started on Angular 7

  •        0
  

We aggregate and tag open source projects. We have collections of more than one million projects. Check out the projects section.



Angular is a platform for building responsive web, native desktop and native mobile applications. Angular client applications are built using HTML, CSS and Typescript. Typescript is a typed superset of Javascript that compiles to plain Javascript. Angular core and optional modules are built using Typescript. Code has been licensed as MIT License.

In this article, we will guide you through to install Angular 7 and we will build web applications to display the products which will have functionality to edit, delete, create and search operation on the catalog. While creating the angular applications, will provide the details about the fundamentals.

Prerequisites for Installation

Angular requires NodeJS version, it is a Javascript runtime build environment. It can be downloaded from the NodeJS website, based on your OS download and install respective binary. It also requires npm, node package manager(npm) to download the packages and its dependency libraries.

hostname:~$ node -v
v10.16.0

hostname:~$ npm -v
3.5.2

Installation

First install angular CLI interface with following command

  npm install -g @angular/cli

Verify the angular CLI command installed as below

 nagappan@nagappan-Latitude-E5450:~/AngularProjects$ ng version

 Angular CLI: 7.3.9
 Node: 10.16.0
 OS: linux x64
 Angular:
 ...

 Package Version
 ------------------------------------------------------
 @angular-devkit/architect 0.13.9
 @angular-devkit/core 7.3.9
 @angular-devkit/schematics 7.3.9
 @schematics/angular 7.3.9
 @schematics/update 0.13.9
 rxjs 6.3.3
 typescript 3.2.4

Now create app from sample app shell below

  ng new my-app

App can be started and home page automatically opens in browser for the below command

 cd my-app
 ng serve --open

File structure of the app will look like as it shown in below image. Also all the code snippets are marked at the top with the filenames.

Angular source structure

Create Product Catalog

The basic building blocks of an Angular application are NgModules, which provide a compilation context for components. An angular app will certainly have one root module that enables bootstrapping in main.ts file as shown below and set of features as modules.

File: src/main.ts

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


NgModule will have components which define the view with template html and css file and shows behaviour based on data. Now AppModule will invoke the src/app/app.module.ts file. In this file the major things are

  • imports - imports the ng module required for the application. browser module imported for different browser platform on dynamic, forms module imported for entering product details.
  • declarations - Components for the module are defined. Appcomponent is the main component and product component responsbile for the catalog.
  • providers - Providers are for providing services
  • bootstrap - main application view, called the root component, which hosts all other app views. Only the root NgModule should set the bootstrap property
    Appcomponent is the root component to be bootstrapped.
       

File: src/app/app.module.ts

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

AppComponent is the bootstrap component which will host the view of product catalog by ProductsComponent. Component is the special decorator with template and css styles. Component view will be injected in all the place where app-root(<app-root>) tag is mentioned as it works based on selector attribute mentioned below.

File: src/app/app.component.ts


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

 App component template file will be marked up with app product component tag <app-products>

File: src/app/app.component.html

 <div style="text-align:center"> 
 <h1>
 {{ title }}!
 </h1>
 <app-products></app-products>
 </div>


Product Entity

Product entity has to be created and set of products should be available to render the view.

File: src/app/Product.ts has been defined as product entity.

  export class Product {
   id: number;
   name: string;
   qty: number;
   brand: string;
   desc: string;
 }

Mock products added as prerequisites for CRUD operations.

File: src/app/mock-products.ts

 import {Product} from './product';

 export var PRODUCTS: Product[] = [
   {id: 11, name: 'Inspiron Laptop', qty: 3, brand: 'Dell',
   desc: 'It is a 14 inch wide screen laptop. Windows OS with Interl Processor 5'},
   {id: 12, name: 'Power X ', qty: 5, brand: 'LG',
   desc: 'It has 2300mAH battery and free mobile cover case'},
   {id: 13, name: 'Keyboard', qty: 7, brand: 'TVS Gold Keyboard',
   desc: 'Its of standard size. It has provision for USB connector'}
 ];

 

CRUD operation

Product component will be invoked to render the html view which has search and add options at the top. Then the card for each product will be appearing by below html template. ngfor directive iterates through products array and create product card. ngIf directive is for toggling the card to view and edit mode. As of now for displaying the card will be in view mode which is based on selectedProduct.

File: src/app/products/products.component.html

 <div class="catalog">
    <div class="card cardsize clickable" *ngFor="let product of products" (click)="onSelect(product)">
    <div *ngIf="selectedProduct!=product" class="card-body">
    <h2 class="card-title">{{product.name | titlecase}}<button class="delete" (click)="onDelete(product)">X</button></h2>
    <p class="card-subtitle">Product Details</p>
         <p class="card-text"><span class="propertyname">Id:</span>{{product.id}}</p>
         <p class="card-text"><span class="propertyname">Qty:</span>{{product.qty}}</p>
         <p class="card-text"><span class="propertyname">Desc:</span>{{product.desc}}</p>
  </div>
</div>


Search Operation And Add Operation are shown by the below div block

File: src/app/products/products.component.html
 

<div>
  <input [(ngModel)]="searchText" placeholder="product name"/>
  <button class="btn btn-primary" type="button" (click)="onSearch(searchText)">Search Product</button>
  <button class="btn btn-primary" type="button" (click)="onAdd(product)">Add Product</button>
</div>


When the card is clicked for edit mode, the card toggles to show up the form for entering the details. Likewise when add product is clicked, new card created with display of the form modules.

File: src/app/products/products.component.html

 <div class="catalog">
    <div class="card cardsize clickable" *ngFor="let product of products" (click)="onSelect(product)">
       <div *ngIf="selectedProduct==product">
          <h2 class="card-title">Create/Edit Product<button class="delete" (click)="onDelete(product)">X</button></h2>
          <form (ngSubmit)="onSubmit(product)">
               <label>Name:</label><input [(ngModel)]="selectedProduct.name" name="productName placeholder="product name"/>
                <br/>
                <div style="width: 7rem;">
                <label>Qty:</label><input [(ngModel)]="selectedProduct.qty" name="productQty" style="width:3rem;" type="number" placeholder="product qty"/>
                </div>
                <label>Brand:</label><input [(ngModel)]="selectedProduct.brand" name="productBrand" placeholder="product brand"/>
                <br/>
                <label>Desc:</label><input [(ngModel)]="selectedProduct.desc" name="productDesc" placeholder="product desc"/><br/>
                <input style="float:right; width: 5rem;" type="submit" value="Save" />
          </form>
     </div>
..............
..............
   </div>
</div>


Angular html backed up by the angular component which provides the list of products to display. For each operation like delete, add, edit(onselct) event methods has been written in the component.ts. For add and edit, card is in edit mode which invokes submit event method to update the products model.

File: src/app/products/product.component.ts

 import { Component, OnInit } from '@angular/core';
 import { Product } from '../product';
 import { PRODUCTS } from '../mock-products';

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

 export class ProductsComponent implements OnInit {

    products = PRODUCTS; /* takes the mock products and display the products for view */


   selectedProduct: Product; /*On click of the card, it takes that product to selectedProduct variable*/

   lastProductId: number; /* it is running counter for the products */


   constructor() {
          this.selectedProduct = null;
          this.lastProductId = this.products.length;
   }

   ngOnInit() {
   }

   /*when click on product card, the selectedProduct is cached by the class member.*/
   onSelect(product: Product) : void {
      console.log("product selected");
      this.selectedProduct = product;
   }

   /* while clicking on add product, the product entity created with available id and pushed to products array. */
   onAdd(product: Product): void {
      console.log("product added");
      this.lastProductId++;
      product = {id: this.lastProductId, name: '', qty: 0, brand: '', desc: ''};
      this.selectedProduct = product;
      this.products.push(product);
  }

  /* while searching, the product name search field value given will be searched in each product name field. */
  onSearch(searchText: string) : void {
       alert(searchText);
      this.products = this.products.filter(p1 => p1.name.indexOf(searchText)>=0);
 }

 /* while delete is clicked, the product will be removed from the products modal. */
 onDelete(product: Product) : void {
    this.products = this.products.filter(p1 => p1!=product);
 }

 /* As the product is double binded, when edit or add product is done, it automatically applies to the products model */
  onSubmit(product: Product) {
     console.log(product);
     this.selectedProduct = null;
  }
}

When we do ng serve --open inside the project folder, we get screen as below:

angular product view

 

Reference:

Code Samples: https://github.com/nagappan080810/angular7projects/tree/master/angular-product-catalog

https://angular.io/guide/architecture-modules

https://angular.io/

https://www.typescriptlang.org/

 


Sponsored:
To find embedded technology information about MCU, IoT, AI etc Check out embedkari.com.


   

Nagappan is a techie-geek and a full-stack senior developer having 10+ years of experience in both front-end and back-end. He has experience on front-end web technologies like HTML, CSS, JAVASCRIPT, Angular and expert in Java and related frameworks like Spring, Struts, EJB and RESTEasy framework. He hold bachelors degree in computer science and he is very passionate in learning new technologies.

Subscribe to our newsletter.

We will send mail once in a week about latest updates on open source tools and technologies. subscribe our newsletter



Related Articles

Angular Service Workers Usage Guide

  • angular service-worker offline-app

Web developers come across scenarios like web application completely breaks when workstation goes offline. Likewise to get into our application, every time we need to open a browser and then access it. Instead if it is in app, it will be easy to access for end-user. Push notifications similar to email client need to be done through web application. All these are addressed by a magic called service worker.

Read More


Push Notifications using Angular

  • angular push-notifications notifications

Notifications is a message pushed to user's device passively. Browser supports notifications and push API that allows to send message asynchronously to the user. Messages are sent with the help of service workers, it runs as background tasks to receive and relay the messages to the desktop if the application is not opened. It uses web push protocol to register the server and send message to the application. Once user opt-in for the updates, it is effective way of re-engaging users with customized content.

Read More


JHipster - Generate simple web application code using Spring Boot and Angular

  • jhipster spring-boot angular web-application

JHipster is one of the full-stack web app development platform to generate, develop and deploy. It provides the front end technologies options of React, Angular, Vue mixed with bootstrap and font awesome icons. Last released version is JHipster 6.0.1. It is licensed under Apache 2 license.

Read More


SeoToaster: easy, fast and efficient open source CMS for top SEO performance

  • cms content-management-system seo ecommerce

SeoToaster is a free Open Source CMS & Ecommerce solution to build, manage and market websites optimized for for top search engine performance. As the name implies, Seo Toaster is to date the only content management system (CMS) to truly integrate SEO execution and web marketing automation technology in full compliance with the search engines industry’s best practices.

Read More


Best open source Text Editors

  • text-editor editor tools dev-tools

Text editors are mainly used by programmers and developers for manipulating plain text source code, editing configuration files or preparing documentation and even viewing error logs. Text editors is a piece of software which enables to create, modify and delete files that a programmer is using while creating website or mobile app.In this article, we will discuss about top 7 all-round performing text editors which is highly supportive for programmers.

Read More



React Patent Clause Licensing issue. Is it something to worry?

  • react react-license facebook

React libraries from Facebook is one of the most used UI libraries. It is competitive to AngularJS. There are many open source UI components or frameworks available but mostly people narrow down to two choices Angular / React. Recently Facebook has updated React license and added a patent clause which makes companies to worry and rethink whether to use React or not.

Read More


PrestaShop - A feature rich Open Source eCommerce solution

PrestaShop is an Open Source eCommerce Solution. It comes complete with over 310 features that have been carefully developed to assist business owners in increasing sales with virtually little effort. It is being used in more than 150,000 online stores.

Read More


Scene.js - Library to Create Timeline-Based Animation

  • scenejs css timeline javascript animation motion

Scene.js is a JavaScript timeline-based animation library for creating animation websites. As an animated timeline library, it allows you to create a chronological order of movements and positions of objects.

Read More


Struts 1.x End Of Life. Whats alternative?

  • java eol struts

The Apache Struts Project Team announced End of Life (EOL) for Struts 1.x web framework. Struts was launched in the year 2000. It is only of the widely used web framework. It gave better control over writing UI and business logic code directly in to JSPs.

Read More


Exonum Blockchain Framework by the Bitfury Group

  • blockchain bitcoin hyperledger blockchain-framework

Exonum is an extensible open source blockchain framework for building private blockchains which offers outstanding performance, data security, as well as fault tolerance. The framework does not include any business logic, instead, you can develop and add the services that meet your specific needs. Exonum can be used to build various solutions from a document registry to a DevOps facilitation system.

Read More


Microweber CMS - An open source CMS with Ecommerce support

  • cms e-commerce microweber

To the user's satisfaction, there is a whole wide world of different CMS, all suitable for different needs. You can go for the giants like Wordpress or Joomla or pick one of the rising forces - Shopify, Squarespace or others. Microweber CMS fills a hole in the current technological ecosystem, aimed at delivering a light software that is perfect for all end-users lacking the technical knowledge needed for complicated website building.

Read More


Light4j Cookbook - Rest API, CORS and RDBMS

  • light4j sql cors rest-api

Light 4j is a fast, lightweight and cloud-native microservices framework. In this article, we will see what and how hybrid framework works and integrate with RDMS databases like MySQL, also built in option of CORS handler for in-flight request.

Read More


Getting Started on Undertow Server

  • java web-server undertow rest

Undertow is a high performing web server which can be used for both blocking and non-blocking tasks. It is extermely flexible as application can assemble the parts in whatever way it would make sense. It also supports Servlet 4.0, JSR-356 compliant web socket implementation. Undertow is licensed under Apache License, Version 2.0.

Read More


Holistic usage guide for OpenSSL

  • openssl security certificate tools

OpenSSL is a general purpose cryptographty toolkit that provides an open source implementation of Transport Layer Security(TLS) and Secure Socket Layer(SSL) protocols. It is written in C,assembly and Perl language but wrappers are available in all languages. This article explains about OpenSSL commands.

Read More


GreenMail - Email Test Framework in Java

  • email email-server test automation

In any project there will be a need to send mail out to users. It could be an alert mail, forget password or authentication related mail. Mail is the default communication between the software and the users. As a developer, we can write code, to send out a mail but we need to make sure whether it got successfully received and how the body of mail, Is it the same like what we have sent. GreenMail is a Email test framework which helps to send and receive mails. It is a test framework which supports SMTP, POP3, IMAP including SSL.

Read More


Activiti - Open Source Business Automation

  • business-automation business bpm

Activiti Cloud is the first Cloud Native BPM framework built to provide a scalable and transparent solution for BPM implementations in cloud environments. The BPM discipline was created to provide a better understanding of how organisations do their work and how this work can be improved in an iterative fashion.

Read More


Introduction to Light 4J Microservices Framework

  • light4j microservice java programming framework

Light 4j is fast, lightweight, secure and cloud native microservices platform written in Java 8. It is based on pure HTTP server without Java EE platform. It is hosted by server UnderTow. Light-4j and related frameworks are released under the Apache 2.0 license.

Read More


Benefits in contributing to Open Source

  • open-source opensource contribute benifits

What the benefit will i get, if i contribute to Open Source? This is the frequently asked question by many people. I just want to pen down the benefits which i know and i hope you will agree with it.

Read More


Connect to MongoDB and Perform CRUD using Java

  • java mongodb database programming

MongoDB is a popular and widely used open source NoSQL database. MongoDB is a distributed database at its core, so high availability, horizontal scaling, and geographic distribution is quite possible. It is licensed under Server Side Public License. Recently they moved to Server Side Public License, before that MongoDB was released under AGPL. This article will provide basic example to connect and work with MongoDB using Java.

Read More


8 Reasons Why Python Scores Over PHP for Web Development

  • python php web-development

PHP, the general-purpose scripting language has been used since decades for socket programming and web development. But in recent times, Python has become the most sought after programming language. This all-purpose programming language is attracting more developers in the industry owing to its highly dynamic and extensible nature. Let's see how Python is winning over age-old PHP.

Read More