Angular Essentials
Angular Essentials
CONTENTS
öö ANGULAR ESSENTIALS
Angular öö
öö
öö
ANGULAR’S BASIC ARCHITECTURE
COMPONENTS
Essentials
öö DATA BINDING
öö COMPONENT COMMUNICATION
öö DIRECTIVES
created and maintained by Google. It serves as a total rewrite to • Syntax: Angular has a different expression syntax for event
AngularJS, and the "Angular" name is meant to include all versions of and property binding.
the framework starting from 2 and up.
• Dynamic loading: Angular will load libraries into memory at
TypeScript is the core of Angular, being the language upon which run-time, retrieve and execute functions, and then unload the
Angular is written. As such, Angular implements major and library from memory.
core functionalities as TypeScript libraries while building client • Iterative callbacks: Using RxJS, Angular makes it easier to
applications with additional HTML. compose asynchronous or callback-based code.
This Refcard will go over the essential pieces of Angular and the main
concepts behind working with the ever-growing platform for web-
Ignite UI for Angular
based applications. The fastest Data Grid and Charts for any
modern web & mobile experience!
HOW IS ANGULAR DIFFERENT FROM
ANGULARJS?
FREE TRIAL
In the past, you might have worked with or learned about AngularJS.
There are a few main differences between the two that you need to
know about:
• Modularity: More of Angular's core functionalities have
moved to modules.
1
Ignite UI for Angular
Specialized Angular UI Components for Modern
Experiences Across Mobile & Desktop
Grids & Lists Styling & Themes Data Entry & Display Menus Notifications
Data Grid Theming Icon Navigation Drawer Snack Bar
List View Shadows Mask Directive Navbar Toast
Combo Data Entry & Display Input Groups Services Scheduling
Charts Drop Down Linear Progress CSV Exporter Calendar
Category Buttons Circular Progress Excel Exporter Date Picker
Chart Button Group Virtualization Time Picker
Layouts
Financial Chart Checkbox Chip
Layout Manager
Gauges Switch Interactions Carousel
Bullet Graph Radio Button Dialog Window Bottom Navigation
Linear Gauge Label Slider Card
Radial Gauge Input Ripple Avatar
Badge Toggle Tabs
Overlay
ANGULAR ESSENTIALS
• NgModules: Declares a compilation context for a set of This decorator had the information on how to compile a component's
components that is dedicated to an application domain, a template and how to create an injector at runtime, all within a
workflow, or a related set of capabilities. metadata object. As you could guess, @NgModule serves to identify
and bridge the gap between both its own directives, components, and
• Components: Defines a class that contains application
pipes, and external components that rely on these pieces.
data and logic and works with an HTML template that
defines a view. The exports property also makes some of the module's make-up
public, ensuring that the external components can effectively
• Template: Combines HTML with Angular markup that can
use them.
modify HTML elements before they're displayed.
• Dependency injection: Provides components with needed functions as the "root" module for the application, and the one that
services and gives access to a service class. you would bootstrap to launch the application.
• Routing: Defines a navigation path among the different There are three basic components to the root module, which we'll
application states lets you view application hierarchies. discuss briefly.
This diagram best represents the relationship between the DECLARATIONS ARRAY
building blocks: Components used in an NgModule need to be added to the
declarations array as a way to tell Angular that these specific
components belong to this specific module. On top of this, since only
declarables can be added to the declarations array, you'll find that the
array will be populated with various components, directives, and pipes.
IMPORTS ARRAY
The Imports array contains all dependent modules.
PROVIDERS ARRAY
The Providers array contains all Services dependencies.
SETTING UP THE ENVIRONMENT
In order to set up the environment, you should start by downloading COMPONENTS
Angular with the Angular CLI tool. If you have a machine that doesn't In Angular applications, what you see in the browser (or elsewhere)
have Node.js and npm installed, make sure to download and install is a component. A component consists of the following parts:
them here.
1. A TypeScript class called the Component class
Then, you'll run a global install of the Angular CLI: 2. An HTML file called the template of the component
npm install --g \@angular/cli 3. An optional CSS file for the styling of the component
COMPONENT METADATA
The @Component decorator decorates a class as a component. It is
a function that takes an object as a parameter. In the @Component
A component is a type of directive with its own template. Whatever decorator, we can set the values of different properties to set the
you see in an Angular application is a component. behavior of the component. The most used properties are as follows:
• template
• encapsulation
import { Component, OnInit } from '@angular/core';
• changeDetection
@Component({
• animations
DZO N E .CO M/ RE FCA RDZ
selector: 'app-product',
templateUrl: './product.component.html', • viewProviders
styleUrls: ['./product.component.scss']
}) Apart from the above-mentioned properties, there are also other
export class ProductComponent implements OnInit { properties. Let's look into these important properties one by one.
• HTML template and styles to display data in the app. It is also styles and styleUrls properties. We can create inline styles by
setting the value of the styles property. We can set external style The component must be part of a module. To use a component in a
using styleUrls property. module, first import it and then pass it to declaration array of the module.
PROVIDERS @NgModule({
declarations: [
To inject a service in a component, you pass that to the providers
AppComponent,
array. Component metadata has an array type property called the
ProductComponent
provider. In the providers, we pass a list of services being injected ],
in the component. We will cover this in detail in further sections.
DATA BINDING
CHANGEDETECTION In Angular, data binding determines how data will flow in between
This property determines how the change detector will work for the component class and component template.
the component. We set the ChangeDetectionStrategy of the
component in the property. There are two possible values: Angular provides us three types of data bindings:
1. Default 1. Interpolation
ENCAPSULATION
2. Native
3. None
4. ShadowDom
INTERPOLATION
Angular interpolation is one-way data binding. It is used to pass
TEMPLATE
data from the component class to the template. The syntax of
When you generate a component using Angular CLI, by default,
interpolation is {{propertyname}}.
selector, templateUrl, and styleUrl properties are set. For
ProductComponent, the template is in external HTML file product. Let's say that we have component class as shown below:
component.html.
export class AppComponent {
<p>
product works! product = {
</p>
title: 'Cricket Bat',
price: 500
You can pass data and capture events between the component
};
class and its template using data binding. We will cover this in }
detail in further sections.
We need to pass the product from the component class to the
USING A COMPONENT template. Keep in mind that to keep the example simple, we're hard-
A component can be used inside an Angular application in various ways: coding the value of the product object; however, in a real scenario,
data could be fetched from the database using the API. We can
1. As a root component.
display the value of the product object using interpolation, as shown
2. As a child component. We can use a component inside in the listing below:
another Component.
<h1>Product</h1>
3. Navigate to a component using routing. In this case, the <h2>Title : {{product.title}}</h2>
component will be loaded in RouterOutlet. <h2>Price : {{product.price}}</h2>
changed, the template will be updated with the updated value of the <h1>Product</h1>
PROPERTY BINDING
Angular provides you with a second type of binding called property
binding. The syntax of property binding is the square bracket: []. It
allows for setting the property of HTML elements on a template with
the property from the component class.
So, let's say that you have a component class like the one below:
Angular does not have built-in two-way data binding; however, by
export class AppComponent {
combining property binding and event binding, you can achieve two-
btnHeight = 100;
btnWidth = 100; way data binding.
}
Now, you can set the height and width properties of a button
on a template with the properties of the component class using
DZO N E .CO M/ RE FCA RDZ
property binding.
Angular provides us a directive, ngModel, to achieve two-way data
<button
binding, and it's very easy to use. First, import FormsModule, and
[style.height.px] = 'btnHeight'
[style.width.px] = 'btnWidth' > then you can create two-way data binding:
Add Product
</button export class AppComponent {
Angular property binding is used to set the property of HTML name = 'foo';
elements with the properties of the component class. You can also }
set properties of other HTML elements like image, list, table, etc.
Whenever the property's value in the component class changes, the We can two-way data-bind the name property with an input box:
HTML element property will be updated in the property binding.
<input type="text" [(ngModel)]='name' />
EVENT BINDING
<h2>{{name}}</h2>
Angular provides you with a third type of binding to capture events
raised on templates in a component class. For instance, there's a
As you see, we are using [(ngModel)] to create two-way data-
button on the component template that allows you to call a function
binding between input control and name property. Whenever a
in the component class. You can do this using event binding. The
user changes the value of the input box, the name property will be
syntax behind event binding is (eventname).
updated and vice versa.
For this example, you might have a component class like this:
COMPONENT COMMUNICATION
export class AppComponent {
In Angular, components communicate to each other to share data
addProduct() {
such as object, string, number, array, or HTML.
console.log('add product');
}
To understand component communication, first, we need to
}
understand relationship between components. For example, when
You want to call the addProduct function on the click of a button on two components are not related to each other, they communicate
the template. You can do this using event binding: through an Angular service.
@INPUT
You can pass data from a parent component to a child component
using the @Input decorator. Data could be of any form such as the
primitive type's string, number, object, array, etc.
@Component({
selector: 'app-child',
template: `<h2>Hi {{greetMessage}}</h2>`
})
export class AppChildComponent implements OnInit {
@Input() greetMessage: string;
constructor() {
}
When components are not related to each other, they communicate
ngOnInit() {
using services. Otherwise, they communicate using one of the
various options depending on the communication criteria. Let's
}
explore all the options one by one. }
the @Input() decorator. So essentially, in the child component, we export class AppChildComponent {
} }
@OUTPUT
You can emit the event from the child component to the parent
component using the @Output decorator.
So far, it's very simple to use event binding to get the button to call
the function in the component. Now, let's tweak the requirement a
bit. What if you want to execute a function of AppComponent on the
click event of a button inside AppChildComponent?
}
}
In the parent component AppComponent, the child component element, component, or other directive.
AppChildComponent can be used as shown in the listing below: 3. Structural directives: Change DOM layout by adding or
removing elements.
import { Component, OnInit } from '@angular/core';
@Component({ The basic difference between a component and a directive is that
selector: 'app-root',
a component has a template, whereas an attribute or structural
template: `<app-child
directive does not have a template. Angular has provided us
(valueChange)='displayCounter($event)'></app-child>`
}) many inbuilt structural and attribute directives. Inbuilt structural
export class AppComponent implements OnInit { directives are *ngFor and *ngIf. Attribute directives are NgStyle
ngOnInit() { and NgModel.
}
displayCounter(count) { USING STRUCTURAL DIRECTIVES
console.log(count); *ngIf is a structure directive used to provide an "if" condition to
}
the statements to get executed. If the expression evaluates to a
}
False value, the elements are removed from the DOM, whereas if it
evaluates to True, the element is added to the DOM.
Right now, we are performing the following tasks in the
AppComponent class: Consider the below listing. In this, the *ngIf directive will add div in
DOM if the value of showMessage property is True.
• Using <app-child> in the template.
@Component({
• In the <app-child> element, using event binding to use the selector: 'app-message',
template:`
valueChange event.
<div *ngIf = 'showMessage'>
• Calling the displayCounter function on the Show Message
</div>
valueChange event.
`
The *ngFor structure directive creates DOM elements in a loop. In most cases, you won't have to create custom structural directives;
Consider the below listing. In this, the *ngFor directive will add rows built-in directives should be enough.
@Component({
selector: 'app-message',
template:`
<table>
<tr *ngFor='let f of data'>
<td>{{f.name}}</td>
</tr>
</table>
`
})
CODE CONTINUED ON NEXT COLUMN
Dhananjay Kumar is a Developer Evangelist for Infragistics. He has been awarded the prestigious Microsoft MVP
award nine times. He is an organizer of ng-India, an India Angular Conference
DZone, Inc.
DZone communities deliver over 6 million pages each 150 Preston Executive Dr. Cary, NC 27513
month to more than 3.3 million software developers, 888.678.0399 919.678.0300
architects and decision makers. DZone offers something for
Copyright © 2018 DZone, Inc. All rights reserved. No part of this publication
everyone, including news, tutorials, cheat sheets, research
may be reproduced, stored in a retrieval system, or transmitted, in any form
guides, feature articles, source code and more. "DZone is a or by means electronic, mechanical, photocopying, or otherwise, without
developer’s dream," says PC Magazine. prior written permission of the publisher.