Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

First Components in Angular 6.0

DZone's Guide to

First Components in Angular 6.0

In this post, we will discuss how to develop your first component or program using the Angular 6.0 web application framework.

· Web Dev Zone ·
Free Resource

Jumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.

In today's web development world, Angular is known as one of the most important and used frameworks. Recently, Angular 6.0 version was launched. So, in this post, we will discuss how to develop your first component or program in Angular 6.0.

What Is Angular?

The Angular framework is an open source JavaScript-based framework. It was actually developed by Misko Havery and Adam Abrons in 2009. This framework supports the JavaScript-based MVC (MVVM) framework. As per the Google, the definition of the angular is a below -

“AngularJS is a structural framework for dynamic web applications. It lets you use HTML as your template language and lets you extend HTML's syntax to express your application components clearly and succinctly.”

The most common advantages for which developers like to use Angular from their projects are –

  • It supports MVC Concept
  • It always supports SPA Application (Single Page Applications)
  • It Supports Client Side Templating
  • In this framework, we can perform unit testing very easily.

Prerequisite for Angular

To start development in Angular 6.0, we need to follow the below perquisites: 

  • Install Node.js.
  • Install TypeScript 2.7 or above.
  • Microsoft Visual Studio or Visual Code for writing code.
  • Install lite-server (in case you are using Visual Code) to host and run the application

So, before starting with Angular 6.0, we first need to know how to install the TypeScript tool. To install TypeScript, we first need to install Node.js. The latest version of Node.js can be downloaded from the below URL:

https://nodejs.org/en/

To install TypeScript, we can download the latest version of TypeScript by either using the command line argument in Node.js or using Visual Studio to directly download it from the NuGet Package Manager.

Command line prompt to install TypeScript:

npm install -g typescript 

Command line prompt for install Lite-Server:

npm install -g lite-server 

Project Configuration

Now, we will discuss how to set up the environment for an Angular 6 project. In this post, we will develop our first program in Angular 6. Before getting started, let’s discuss the project configuration files which are required in Angular. An Angular project always contains 3 major configuration files. They are:

  • tsconfig.json – This file contains the compiler options which are required to run the projects.
  • package.json – It is basically a JSON file which contains all the necessary information regarding different packages which are required to run or execute the Angular application.
  • system.config.js – This file act as a configuration file. This file is used to load Node modules which are compiled in TypeScript at the time of execution.

What Is a Component?

The Angular framework is basically a component-based framework (from Angular 2.0 or above). SO, we first need to understand what components are and how they can be defined. In Angular, a component is just like a class in other OOP-based languages. This class is basically defined to display any element on the application screen. So, as per our requirements, we can create, update, or delete any existing component in the application. In TypeScript, we can define the component class with the help of the @Compoent() decorator.

Component Configuration

The @Component decorator actually used to decorate a TypeScript class as a component object. It is a function which takes different types of parameters. In the @component decorator, we can assign different values to properties to fix the behavior of the components. The most used properties are given below:

  • selector: A string value which represents the component on the browser at execution time.
  • template: The value of this property contains the basic HTML code which we will need to display in the browser. It acts as an inline template.
  • templateUrl: Another way of defining the HTML tags in the component. We can create HTML files with proper HTML tags and then we need to provide that file name with the relative path in this attribute. So that at execution time the Angular loader will display the HTML code in the browser for the application. Some people call this process 'external templating.'
  • moduleId: It is used to resolve the related path of the template URL or style URL for the component objects.
  • styles or stylesUrls: It is used to provide the style of the components. We can define inline CSS using styles attribute or provide CSS files with related URLs in the styleUrls attribute.
  • providers: This attribute is basically used for dependency injection purposes. We can inject services, packages, components, etc. using this attribute.

Create an Angular Module

As we already discussed, everything in Angular 6 belongs to an Angular Module. So, for developing the root component, we first need to declare our Angular module. The Angular module can be defined by creating a TypeScript class decorated with the NgModule decorator. In order to use it, we first need to import it as follows:

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

@NgModule()

export class SampleModule { }

tsconfig.json File

{
  "compileOnSave": true,
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    "declaration": false,
    "noStrictGenericChecks": true,
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  },
  "exclude": [
    "node_modules",
    "wwwroot"
  ]
}

package.json File

{
  "name": "angular-sample",
  "version": "6.0.0",
  "private": true,
  "description": "Example project of angular 6",
  "scripts": {
    "build": "tsc -p src/",
    "build:watch": "tsc -p src/ -w",
    "build:e2e": "tsc -p e2e/",
    "serve": "lite-server -c=bs-config.json",
    "serve:e2e": "lite-server -c=bs-config.e2e.json",
    "prestart": "npm run build",
    "start": "concurrently \"npm run build:watch\" \"npm run serve\"",
    "pree2e": "npm run build:e2e",
    "e2e": "concurrently \"npm run serve:e2e\" \"npm run protractor\" --kill-others --success first",
    "preprotractor": "webdriver-manager update",
    "protractor": "protractor protractor.config.js",
    "pretest": "npm run build",
    "test": "concurrently \"npm run build:watch\" \"karma start karma.conf.js\"",
    "pretest:once": "npm run build",
    "test:once": "karma start karma.conf.js --single-run",
    "lint": "tslint ./src/**/*.ts -t verbose"
  },
  "keywords": [],
  "author": "Debasis",
  "license": "MIT",
  "dependencies": {
    "@angular/animations": "6.0.0",
    "@angular/cli": "^6.0.0",
    "@angular/common": "6.0.0",
    "@angular/compiler": "6.0.0",
    "@angular/core": "6.0.0",
    "@angular/forms": "6.0.0",
    "@angular/http": "6.0.0",
    "@angular/platform-browser": "6.0.0",
    "@angular/platform-browser-dynamic": "6.0.0",
    "@angular/router": "6.0.0",
    "@angular/service-worker": "6.0.0",
    "core-js": "^2.4.1",
    "crypto-js": "^3.1.9-1",
    "hammer-timejs": "^1.1.0",
    "hammerjs": "^2.0.8",
    "lodash": "^4.17.4",
    "moment": "^2.20.1",
    "pepjs": "^0.4.3",
    "rxjs": "^6.2.0",
    "rxjs-compat": "^6.2.0",
    "rxjs-system-bundle": "^6.0.0",
    "systemjs": "0.21.3",
    "uuid": "^3.2.1",
    "zone.js": "^0.8.14"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.6.0",
    "@angular/cli": "^6.0.0",
    "@angular/compiler-cli": "^6.0.0",
    "@angular/platform-server": "^6.0.0",
    "@types/jasmine": "~2.8.0",
    "@types/jasminewd2": "^2.0.3",
    "@types/node": "^6.0.45",
    "jasmine-core": "3.1.0",
    "jasmine-spec-reporter": "4.2.1",
    "karma": "2.0.2",
    "karma-chrome-launcher": "2.2.0",
    "karma-cli": "~1.0.1",
    "karma-coverage": "^1.1.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-junit-reporter": "^1.2.0",
    "karma-phantomjs-launcher": "^1.0.4",
    "lodash": "^4.16.2",
    "protractor": "5.3.1",
    "ts-node": "^5.0.1",
    "tslint": "^5.9.1",
    "typescript": "2.7.2",
    "concurrently": "^3.2.0",
    "lite-server": "^2.2.2",
    "canonical-path": "0.0.2",
    "rimraf": "^2.5.4",
    "child-process-promise": "^2.2.1",
    "codelyzer": "4.3.0",
    "del": "^3.0.0",
    "gulp": "^3.9.1",
    "gulp-inline-ng2-template": "^4.1.0",
    "node-sass": "^4.8.3",
    "gulp-replace": "^0.6.1",
    "gulp-sourcemaps": "^2.6.4",
    "gulp-typescript": "^4.0.1",
    "npm-version-up": "^0.1.5",
    "phantomjs-prebuilt": "^2.1.16",
    "puppeteer": "^1.2.0",
    "run-sequence": "^2.2.1",
    "systemjs-builder": "^0.16.12"
  },
  "repository": {}
}

systemjs.config.js File

/**
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
    System.config({
        paths: {
            // paths serve as alias
            'npm:': '/node_modules/',
        },
        // map tells the System loader where to look for things
        map: {
            // our app is within the app folder
            'app': '.',
            '@angular/core': 'npm:@angular/core/bundles/core.umd.min.js',
            '@angular/common': 'npm:@angular/common/bundles/common.umd.min.js',
            '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.min.js',
            '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.min.js',
            '@angular/router': 'npm:@angular/router/bundles/router.umd.min.js',
            '@angular/http': 'npm:@angular/http/bundles/http.umd.min.js',
            '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.min.js',
            '@angular/platform-browser/animations': 'npm:@angular/platform-browser/bundles/platform-browser-animations.umd.min.js',
            '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.min.js',
            '@angular/service-worker': 'npm:@angular/service-worker/bundles/service-worker.umd.min.js',
            '@angular/animations': 'npm:@angular/animations/bundles/animations.umd.min.js',
            '@angular/animations/browser': 'npm:@angular/animations/bundles/animations-browser.umd.min.js',

            // other libraries
            'rxjs': 'npm:rxjs',
            'rxjs-compat': 'npm:rxjs-compat',
            'rxjs-system-bundle': 'npm:rxjs-system-bundle',
            'lodash': 'npm:lodash/index.js',
            'uuid': 'npm:uuid/index.js',
            'crypto': 'npm:crypto-js/crypto-js.js',
            'oidc-client': 'npm:oidc-client/lib/oidc-client.js',
            'tslib': 'npm:tslib/tslib.js',
            'hammerjs': 'npm:hammerjs/hammer.js',
            'hammer-timejs': 'npm:hammer-timejs/hammer-time.js',
            'moment': 'npm:moment/moment.js',
            'core-js': 'npm:core-js',
            'zone.js': 'npm:zone.js',

        },
        // packages tells the System loader how to load when no filename and/or no extension
        packages: {
            app: { main: 'main.js', defaultExtension: 'js' },
            app: { defaultExtension: 'js', },
            rxjs: { defaultExtension: 'js', main: "index.js" },
            "rxjs-compat": { defaultExtension: 'js', main: "index.js" },
            "rxjs/operators": { "main": "index.js", "defaultExtension": "js" },
            "rxjs/internal-compatibility": { "main": "index.js", "defaultExtension": "js" },
            "rxjs/testing": { "main": "index.js", "defaultExtension": "js" },
            'rxjs/ajax': { main: 'index.js', defaultExtension: 'js' },
            'rxjs/webSocket': { main: 'index.js', defaultExtension: 'js' },
            '..': { defaultExtension: 'js' }
        }
    });
})(this);

app.component.welcome.ts File

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

@Component({
    selector: "welcome-prog",
    template: `<h1>First Programe in Angular 6.0. Welcome to Angular World</h1> 
                <br>
                <a  href="../index.html" style="color:red;">
                    <h3>Return to Home</h3>
                </a>
                `
})

export class WelcomeComponent {
    constructor() {
    }
}

app.module.demo.ts File

import { NgModule, NO_ERRORS_SCHEMA, } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { ReactiveFormsModule } from "@angular/forms";
import { HttpModule } from '@angular/http';

import { WelcomeComponent } from './day1/app.component.welcome';

@NgModule({
    imports: [BrowserModule, FormsModule, ReactiveFormsModule, HttpModule],
    declarations: [WelcomeComponent
],
    bootstrap: [WelcomeComponent],
    schemas: [NO_ERRORS_SCHEMA]
})

export class DemoModule { }

main.ts File

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { DemoModule } from './app.module.demo';

platformBrowserDynamic().bootstrapModule(DemoModule);

index.html File

<!DOCTYPE html>
<html lang="en">
<head>
    <!--<base href="/">-->
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">
    <title>Angular 6 - Console</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="keywords" content="">
    <meta name="author" content="">

    <link href="../resource/css/bootstrap.min.css" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="../resource/css/font-awesome.min.css" type="text/css">
    <link rel="stylesheet" href="../resource/css/jquery-ui.css" type="text/css">
    <link href="../resource/css/style.css" rel="stylesheet" type="text/css">
    <link rel="shortcut icon" href="../resource/img/favicon/favicon.ico">
    <link href="../resource/css/app.css" rel="stylesheet"  type="text/css"/>
</head>
<body>
    <div class="content">
        <welcome-prog></welcome>
    </div>        
    <script src="../node_modules/core-js/client/shim.min.js" type="text/javascript"></script>
    <script src="../node_modules/zone.js/dist/zone.js" type="text/javascript"></script>
    <script src="../node_modules/systemjs/dist/system.src.js" type="text/javascript"></script>
    <script src="systemjs.config.js" type="text/javascript"></script>
    <script>
        System.import('../main.js').catch(function (err) { console.error(err); });
    </script>
</body>
</html>

Now enter the command lite-server in the same location as the tsconfig.js file in the command prompt. Lite-server hosts the application at port 3000 of the localhost in the browser.

First Program

Take a look at an Indigo.Design sample application to learn more about how apps are created with design to code software.

Topics:
angular ,javascript ,component ,web dev ,web application development

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}