Angular 6 Quick Guide
Angular 6 Quick Guide
Advertisements
ANGULAR 6 - OVERVIEW
There are five major releases of Angular. The first version that was released is Angular 1, which is also called
AngularJS. Angular 1 WAS followed by Angular 2, which came in with a lot of changes when compared to Angular
1.
The structure of Angular is based on the components/services architecture. AngularJS was based on the model
view controller. Angular 6 released in May 2018 proves to be a major breakthrough and is the latest release from
the Angular team after Angular 5.
Angular 6 is almost the same as Angular 5. It has a backward compatibility with Angular 5. Projects developed in
Angular 5 will work without any issues with Angular 5.
Let us now see the new features and the changes made in Angular 5.
HTTPClient API − HTTPClient API was introduced to deprecate the HTTP library. HTTPClient API is
much faster, secure and efficient than HTTP library.
Multiple export aliases − A component can be exported using multiple aliases to ease the migration
process.
Internationalized Pipes for Number, Date, and Currency − New pipes are introduced for better
standardization.
Lambda support − lambda expressions with proper names can be used instead of functions.
Build Optimizer - Build Optimizer introduced. It optimizes the build size and improves the application
speed. Angular CLI uses Build Optimizer automatically.
Improved Compiler − Compiler from Angular 5 onwards supports incremental compilation leading for
faster compilation. Compiler uses TypeScript transforms, a new feature of TypeScript 2.3 available
onwards.
Updated Angular CLI, Command Line interface − New commands added, like ng-update to migrate
from previous version to current version. ng-add to quickly add application features to make application a
progressive web apps.
Updated CDK, Component Development Kit − Supports creating custom UI elements without need
of angular material library. Supports responsive web design layouts. Supports overlay packages to create
pop-ups.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 1/88
6/13/2019 Angular 6 Quick Guide
Updated Angular Material − New Tree component added, mat-tree, a styled version and cdk-tree, a
unstyled version, to represent a hierarchical structure like tree.
Angular Element − Allows Angular Components to be published as Web Components which can then be
used in any HTML page. Using Angular Element package, native custom elements can be created easily.
Tree Shaking on Services − Now tree shaking can be applied on services as well to remove the dead code.
Nodejs
Npm
Angular CLI
IDE for writing your code
Nodejs has to be greater than 8.11 and npm has to be greater than 5.6.
Nodejs
To check if nodejs is installed on your system, type node -v in the terminal. This will help you see the version of
nodejs currently installed on your system.
C:\>node -v
v8.11.3
If it does not print anything, install nodejs on your system. To install nodejs, go the homepage
https://nodejs.org/en/download/ of nodejs and install the package based on your OS.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 2/88
6/13/2019 Angular 6 Quick Guide
Based on your OS, install the required package. Once nodejs is installed, npm will also get installed along with it.
To check if npm is installed or not, type npm -v in the terminal. It should display the version of the npm.
C:\>npm -v
5.6.0
Angular 4 installations are very simple with the help of angular CLI. Visit the homepage https://cli.angular.io/ of
angular to get the reference of the command.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 3/88
6/13/2019 Angular 6 Quick Guide
You will get the above installation in your terminal, once Angular CLI is installed. You can use any IDE of your
choice, i.e., WebStorm, Atom, Visual Studio Code, etc.
Angular6 uses TypeScript 2.9 version whereas Angular 4 uses TypeScript version 2.2. This brings a lot of
difference in the performance.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 4/88
6/13/2019 Angular 6 Quick Guide
To install Angular 6, the Angular team came up with Angular CLI which eases the installation. You need to run
through a few commands to install Angular 6.
To get started with the installation, we first need to make sure we have nodejs and npm installed with the latest
version. The npm package gets installed along with nodejs.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 5/88
6/13/2019 Angular 6 Quick Guide
The latest version of Nodejs V8.11.3 is recommended for users. Users who already have nodejs greater than 8.11
can skip the above process. Once nodejs is installed, you can check the version of node in the command line using
the command, node -v, as shown below −
node -v
v8.11.3
The command prompt shows V8.11.3. Once nodejs is installed, npm will also get installed along with it.
To check the version of npm, type command npm -v in the terminal. It will display the version of npm as shown
below.
npm -v
v5.6.0
The version of npm is 5.6.0. Now that we have nodejs and npm installed, let us run the angular cli commands to
install Angular 6. You will see the following commands on the webpage −
Let us start with the first command in the command line and see how it works.
To start with, we will create an empty directory wherein, we will run the Angular CLI command.
We have created an empty folder ProjectA4 and installed the Angular CLI command. We have also used -g to
install Angular CLI globally. Now, you can create your Angular 4 project in any directory or folder and you don’t
have to install Angular CLI project wise, as it is installed on your system globally and you can make use of it from
any directory.
Let us now check whether Angular CLI is installed or not. To check the installation, run the following command in
the terminal −
ng -v
_ _ _
/ \ _ _ _ _| | _ _ / | | |_ _|
/ ? \ | '_ \ / _` | | | | |/ _` | ' | | | | | | |
/ \| | | | (_| | |_| | | (_| | | | | | | | |
/_/ \_\_| |_|\ , |\ ,_|_|\ ,_|_| \ | | |
| /
Package Version
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 6/88
6/13/2019 Angular 6 Quick Guide
------------------------------------------------------
@angular-devkit/architect 0.7.3
@angular-devkit/core 0.7.3
@angular-devkit/schematics 0.7.3
@schematics/angular 0.7.3
@schematics/update 0.7.3
rxjs 6.2.2
typescript 2.9.2
We get the @angular/cli version, which is at present 6.1.3. The node version running is 8.11.3 and also the OS
details. The above details tell us that we have installed angular cli successfully and now we are ready to commence
with our project.
We have now installed Angular 6. Let us now create our first project in Angular 6. To create a project in Angular 6,
we will use the following command −
ng new projectname
ng new Angular6App
CREATE Angular6App/angular.json (3593 bytes)
CREATE Angular6App/package.json (1317 bytes)
CREATE Angular6App/README.md (1028 bytes)
CREATE Angular6App/tsconfig.json (408 bytes)
CREATE Angular6App/tslint.json (2805 bytes)
CREATE Angular6App/.editorconfig (245 bytes)
CREATE Angular6App/.gitignore (503 bytes)
CREATE Angular6App/src/favicon.ico (5430 bytes)
CREATE Angular6App/src/index.html (298 bytes)
CREATE Angular6App/src/main.ts (370 bytes)
CREATE Angular6App/src/polyfills.ts (3194 bytes)
CREATE Angular6App/src/test.ts (642 bytes)
CREATE Angular6App/src/styles.css (80 bytes)
CREATE Angular6App/src/browserslist (375 bytes)
CREATE Angular6App/src/karma.conf.js (964 bytes)
CREATE Angular6App/src/tsconfig.app.json (170 bytes)
CREATE Angular6App/src/tsconfig.spec.json (256 bytes)
CREATE Angular6App/src/tslint.json (314 bytes)
CREATE Angular6App/src/assets/.gitkeep (0 bytes)
CREATE Angular6App/src/environments/environment.prod.ts (51 bytes)
CREATE Angular6App/src/environments/environment.ts (642 bytes)
CREATE Angular6App/src/app/app.module.ts (314 bytes)
CREATE Angular6App/src/app/app.component.html (1141 bytes)
CREATE Angular6App/src/app/app.component.spec.ts (1010 bytes)
CREATE Angular6App/src/app/app.component.ts (215 bytes)
CREATE Angular6App/src/app/app.component.css (0 bytes)
CREATE Angular6App/e2e/protractor.conf.js (752 bytes)
CREATE Angular6App/e2e/tsconfig.e2e.json (213 bytes)
CREATE Angular6App/e2e/src/app.e2e-spec.ts (307 bytes)
CREATE Angular6App/e2e/src/app.po.ts (208 bytes)
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 7/88
6/13/2019 Angular 6 Quick Guide
The project Angular6App is created successfully. It installs all the required packages necessary for our project to
run in Angular 6. Let us now switch to the project created, which is in the directory Angular6App. Change the
directory in the command line - cd Angular 6-app.
We will use Visual Studio Code IDE for working with Angular 6; you can use any IDE, i.e., Atom, WebStorm, etc.
To download Visual Studio Code, go to https://code.visualstudio.com/ and click Download for Windows.
Click Download for Windows for installing the IDE and run the setup to start using IDE.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 8/88
6/13/2019 Angular 6 Quick Guide
We have not started any project in it. Let us now take the project we have created using angular-cli.
Now that we have the file structure for our project, let us compile our project with the following command −
ng serve
The ng serve command builds the application and starts the web server.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 9/88
6/13/2019 Angular 6 Quick Guide
The web server starts on port 4200. Type the url HTTP://LOCALHOST:4200/ in the browser and see the output.
You will be directed to the following screen −
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 10/88
6/13/2019 Angular 6 Quick Guide
We have made changes in the files - app.component.html and app.component.ts. We will discuss more
about this in our subsequent chapters.
Let us complete the project setup. If you see we have used port 4200, which is the default port that angular-cli
makes use of while compiling. You can change the port if you wish using the following command −
E2 E −end to end test folder. Mainly E2E is used for integration testing and helps ensure the application
works fine.
node_modules − The npm package installed is node_modules. You can open the folder and see the
packages available.
src − This folder is where we will work on the project using Angular 4.
.gitignore − A .gitignore file should be committed into the repository, in order to share the ignore rules
with any other users that clone the repository.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 11/88
6/13/2019 Angular 6 Quick Guide
karma.conf.js − This is used for unit testing via the protractor. All the information required for the
project is provided in karma.conf.js file.
package.json − The package.json file tells which libraries will be installed into node_modules when you
run npm install.
At present, if you open the file in the editor, you will get the following modules added in it.
"@angular/animations": "^6.1.0",
"@angular/common": "^6.1.0",
"@angular/compiler": "^6.1.0",
"@angular/core": "^6.1.0",
"@angular/forms": "^6.1.0",
"@angular/http": "^6.1.0",
"@angular/platform-browser": "^6.1.0",
"@angular/platform-browser-dynamic": "^6.1.0",
"@angular/router": "^6.1.0",
"core-js": "^2.5.4",
"rxjs": "^6.0.0",
"zone.js": "~0.8.26"
In case you need to add more libraries, you can add those over here and run the npm install command.
tsconfig.json − This basically contains the compiler options required during compilation.
tslint.json − This is the config file with rules to be considered while compiling.
The src folder is the main folder, which internally has a different file structure.
app
It contains the files described below. These files are installed by angular-cli by default.
app.module.ts − If you open the file, you will see that the code has reference to different libraries, which
are imported. Angular-cli has used these default libraries for the import - angular/core, platform-browser.
The names itself explain the usage of the libraries.
They are imported and saved into variables such as declarations, imports, providers, and bootstrap.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 12/88
6/13/2019 Angular 6 Quick Guide
declarations − In declarations, the reference to the components is stored. The Appcomponent is the default
component that is created whenever a new project is initiated. We will learn about creating new components in a
different section.
imports − This will have the modules imported as shown above. At present, BrowserModule is part of the
imports which is imported from @angular/platform-browser.
providers − This will have reference to the services created. The service will be discussed in a subsequent
chapter.
bootstrap − This has reference to the default component created, i.e., AppComponent.
app.component.css − You can write your css structure over here. Right now, we have added the
background color to the div as shown below.
.divdetails{
background-color: #ccc;
}
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 13/88
6/13/2019 Angular 6 Quick Guide
<h2>
<a target = "_blank" href = "https://github.com/angular/angular-cli/wiki">
CLI Documentation
</a>
</h2>
</li>
<li>
<h2>
<a target = "_blank" href="http://angularjs.blogspot.ca/">Angular blog</a>
</h2>
</li>
</ul>
</div>
This is the default html code currently available with the project creation.
app.component.spec.ts − These are automatically generated files which contain unit tests for source
component.
app.component.ts − The class for the component is defined over here. You can do the processing of the
html structure in the .ts file. The processing will include activities such as connecting to the database,
interacting with other components, routing, services, etc.
Assets
Environment
This folder has the details for the production or the dev environment. The folder contains two files.
environment.prod.ts
environment.ts
Both the files have details of whether the final file should be compiled in the production environment or the dev
environment.
The additional file structure of Angular 4 app folder includes the following −
favicon.ico
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 14/88
6/13/2019 Angular 6 Quick Guide
index.html
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>HTTP Search Param</title>
<base href = "/">
<link href = "https://fonts.googleapis.com/icon?family=Material+Icons" rel = "stylesheet">
<link href = "https://fonts.googleapis.com/css?family=Roboto|Roboto+Mono" rel =
"stylesheet">
<link href = "styles.c7c7b8bf22964ff954d3.bundle.css" rel = "stylesheet">
<meta name = "viewport" content = "width = device-width, initial-scale = 1">
<link rel = "icon" type = "image/x-icon" href = "favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>
The body has <app-root></app-root>. This is the selector which is used in app.component.ts file and will
display the details from app.component.html file.
main.ts
main.ts is the file from where we start our project development. It starts with importing the basic module which
we need. Right now if you see angular/core, angular/platform-browser-dynamic, app.module and environment is
imported by default during angular-cli installation and project setup.
platformBrowserDynamic().bootstrapModule(AppModule);
When AppModule is called, it calls app.module.ts which further calls the AppComponent based on the boostrap as
follows −
bootstrap: [AppComponent]
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 15/88
6/13/2019 Angular 6 Quick Guide
In app.component.ts, there is a selector: app-root which is used in the index.html file. This will display the
contents present in app.component.html.
polyfill.ts
styles.css
test.ts
Here, the unit test cases for testing the project will be handled.
tsconfig.app.json
This is used during compilation, it has the config details that need to be used to run the application.
tsconfig.spec.json
typings.d.ts
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 16/88
6/13/2019 Angular 6 Quick Guide
ANGULAR 6 - COMPONENTS
Major part of the development with Angular 6 is done in the components. Components are basically classes that
interact with the .html file of the component, which gets displayed on the browser. We have seen the file structure
in one of our previous chapters. The file structure has the app component and it consists of the following files −
app.component.css
app.component.html
app.component.spec.ts
app.component.ts
app.module.ts
The above files were created by default when we created new project using the angular-cli command.
If you open up the app.module.ts file, it has some libraries which are imported and also a declarative which is
assigned the appcomponent as follows −
The declarations include the AppComponent variable, which we have already imported. This becomes the parent
component.
Now, angular-cli has a command to create your own component. However, the app component which is created
by default will always remain the parent and the next components created will form the child components.
When you run the above command in the command line, you will receive the following output −
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 17/88
6/13/2019 Angular 6 Quick Guide
Now, if we go and check the file structure, we will get the new-cmp new folder created under the src/app folder.
If you see the above new-cmp.component.ts file, it creates a new class called NewCmpComponent, which
implements OnInit.In, which has a constructor and a method called ngOnInit. ngOnInit is called by default when
the class is executed.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 18/88
6/13/2019 Angular 6 Quick Guide
Let us check how the flow works. Now, the app component, which is created by default becomes the parent
component. Any component added later becomes the child component.
When we hit the url in the HTTP://LOCALHOST:4200/ browser, it first executes the index.html file which is shown
below −
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>Angular 6 Application</title>
<base href = "/">
<meta name = "viewport" content = "width = device-width, initial-scale = 1">
<link rel = "icon" type = "image/x-icon" href = "favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>
The above is the normal html file and we do not see anything that is printed in the browser. Take a look at the tag
in the body section.
<app-root></app-root>
This is the root tag created by the Angular by default. This tag has the reference in the main.ts file.
AppModule is imported from the app of the main parent module, and the same is given to the bootstrap Module,
which makes the appmodule load.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 19/88
6/13/2019 Angular 6 Quick Guide
bootstrap: [AppComponent]
})
Here, the AppComponent is the name given, i.e., the variable to store the reference of the app. Component.ts
and the same is given to the bootstrap. Let us now see the app.component.ts file.
Angular core is imported and referred as the Component and the same is used in the Declarator as −
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
In the declarator reference to the selector, templateUrl and styleUrl are given. The selector here is nothing but
the tag which is placed in the index.html file that we saw above.
The class AppComponent has a variable called title, which is displayed in the browser.
It has just the html code and the variable title in curly brackets. It gets replaced with the value, which is present in
the app.component.ts file. This is called binding. We will discuss the concept of binding in a subsequent
chapter.
Now that we have created a new component called new-cmp. The same gets included in the app.module.ts file,
when the command is run for creating a new component.
new-cmp.component.ts
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 20/88
6/13/2019 Angular 6 Quick Guide
Here, we have to import the core too. The reference of the component is used in the declarator.
The declarator has the selector called app-new-cmp and the templateUrl and styleUrl.
<p>
new-cmp works!
</p>
As seen above, we have the html code, i.e., the p tag. The style file is empty as we do not need any styling at
present. But when we run the project, we do not see anything related to the new component getting displayed in
the browser. Let us now add something and the same can be seen in the browser later.
The selector, i.e., app-new-cmp needs to be added in the app.component .html file as follows −
When the <app-new-cmp></app-new-cmp> tag is added, all that is present in the .html file of the new
component created will get displayed on the browser along with the parent component data.
Let us see the new component .html file and the new-cmp.component.ts file.
new-cmp.component.ts
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 21/88
6/13/2019 Angular 6 Quick Guide
In the class, we have added one variable called new component and the value is "Entered in new component
created".
<p>
{{newcomponent}}
</p>
<p>
new-cmp works!
</p>
Now since we have included the <app-new-cmp></app-new-cmp> selector in the app. component .html
which is the .html of the parent component, the content present in the new component .html file
new − cmp. component. html gets displayed on the browser as follows −
Similarly, we can create components and link the same using the selector in the app.component.html file as
per our requirements.
ANGULAR 6 - MODULES
Module in Angular refers to a place where you can group the components, directives, pipes, and services, which
are related to the application.
In case you are developing a website, the header, footer, left, center and the right section become part of a module.
To define module, we can use the NgModule. When you create a new project using the Angular -cli command,
the ngmodule is created in the app.module.ts file by default and it looks as follows −
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 22/88
6/13/2019 Angular 6 Quick Guide
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
It starts with @NgModule and contains an object which has declarations, import s, providers and bootstrap.
Declaration
It is an array of components created. If any new component gets created, it will be imported first and the
reference will be included in declarations as shown below −
declarations: [
AppComponent,
NewCmpComponent
]
Import
It is an array of modules required to be used in the application. It can also be used by the components in the
Declaration array. For example, right now in the @NgModule we see the Browser Module imported. In case your
application needs forms, you can include the module as follows −
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 23/88
6/13/2019 Angular 6 Quick Guide
imports: [
BrowserModule,
FormsModule
]
Providers
Bootstrap
This includes the main app component for starting the execution.
The variable in the app.component.html file is referred as {{title}} and the value of title is initialized in the
app.component.ts file and in app.component.html, the value is displayed.
Let us now create a dropdown of months in the browser. To do that , we have created an array of months in
app.component.ts as follows −
The month's array that is shown above is to be displayed in a dropdown in the browser. For this, we will use the
following line of code −
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 24/88
6/13/2019 Angular 6 Quick Guide
We have created the normal select tag with option. In option, we have used the for loop. The for loop is used to
iterate over the months' array, which in turn will create the option tag with the value present in the months.
The syntax for in Angular is *ngFor = "let I of months" and to get the value of months we are displaying it in
{{i}}.
The two curly brackets help with data binding. You declare the variables in your app.component.ts file and the
same will be replaced using the curly brackets.
Let us see the output of the above month's array in the browser
The variable that is set in the app.component.ts can be bound with the app.component.html using the curly
brackets; for example, {{}}.
Let us now display the data in the browser based on condition. Here, we have added a variable and assigned the
value as true. Using the if statement, we can hide/show the content to be displayed.
Example
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 25/88
6/13/2019 Angular 6 Quick Guide
Output
Let us try the above example using the IF THEN ELSE condition.
Example
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 26/88
6/13/2019 Angular 6 Quick Guide
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 4 Project!';
//array of months.
months = ["January", "February", "March", "April",
"May", "June", "July", "August", "September",
"October", "November", "December"];
isavailable = false;
}
In this case, we have made the isavailable variable as false. To print the else condition, we will have to create
the ng-template as follows −
If is used with the else condition and the variable used is condition1. The same is assigned as an id to the ng-
template, and when the available variable is set to false the text Condition is invalid is displayed.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 27/88
6/13/2019 Angular 6 Quick Guide
Now, we will make the variable isavailable as true. In the html, the condition is written in the following way −
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 28/88
6/13/2019 Angular 6 Quick Guide
If the variable is true, then condition1, else CONDITION2. Now, two templates are created with id #condition1
and #CONDITION2.
app.component.html
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 29/88
6/13/2019 Angular 6 Quick Guide
<br/>
<div>
<span *ngIf = "isavailable; then condition1 else condition2">
Condition is valid.
</span>
<ng-template #condition1>Condition is valid</ng-template>
<ng-template #condition2>Condition is invalid</ng-template>
</div>
<button (click)="myClickFunction($event)">
Click Me
</button>
In the app.component.html file, we have defined a button and added a function to it using the click event.
(click)="myClickFunction($event)"
Upon clicking the button, the control will come to the function myClickFunction and a dialog box will appear,
which displays the Button is clicked as shown in the following screenshot −
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 30/88
6/13/2019 Angular 6 Quick Guide
The following line of code will help you add the change event to the dropdown −
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 31/88
6/13/2019 Angular 6 Quick Guide
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 6 Project!';
//array of months.
months = ["January", "Feburary", "March", "April",
"May", "June", "July", "August", "September",
"October", "November", "December"];
isavailable = true;
myClickFunction(event) {
alert("Button is clicked");
console.log(event);
}
changemonths(event) {
console.log("Changed month from the Dropdown");
console.log(event);
}
}
The console message "Changed month from the Dropdown" is displayed in the console along with the event.
Let us add an alert message in app.component.ts when the value from the dropdown is changed as shown
below −
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 32/88
6/13/2019 Angular 6 Quick Guide
isavailable = true;
myClickFunction(event) {
//just added console.log which will display the event details in browser
on click of the button.
alert("Button is clicked");
console.log(event);
}
changemonths(event) {
alert("Changed month from the Dropdown");
}
}
When the value in dropdown is changed, a dialog box will appear and the following message will be displayed -
"Changed month from the Dropdown".
ANGULAR 6 - TEMPLATES
Angular 6 uses the <ng-template> as the tag similar to Angular 4 instead of <template> which is used in
ANGULAR2. The reason Angular 4 changed <template> to <ng-template> is because there is a name conflict
between the <template> tag and the html <template> standard tag. It will deprecate completely going ahead.
Let us now use the template along with the if else condition and see the output.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 33/88
6/13/2019 Angular 6 Quick Guide
app.component.html
For the Span tag, we have added the if statement with the else condition and will call template CONDITION1, else
CONDITION2.
If the condition is true, then the CONDITION1 template is called, otherwise CONDITION2.
app.component.ts
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 34/88
6/13/2019 Angular 6 Quick Guide
The variable isavailable is false so the CONDITION2 template is printed. If you click the button, the respective
template will be called. If you inspect the browser, you will see that you never get the span tag in the dom. The
following example will help you understand the same.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 35/88
6/13/2019 Angular 6 Quick Guide
If you inspect the browser, you will see that the dom does not have the span tag. It has the Condition is invalid
from template in the dom.
The following line of code in html will help us get the span tag in the dom.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 36/88
6/13/2019 Angular 6 Quick Guide
</div>
<button (click)="myClickFunction($event)">Click Me</button>
If we remove the then condition, we get the "Condition is valid" message in the browser and the span tag is
also available in the dom. For example, in app.component.ts, we have made the isavailable variable as true.
ANGULAR 6 - DIRECTIVES
Directives in Angular is a js class, which is declared as @directive. We have 3 directives in Angular. The
directives are listed below −
Component Directives
These form the main class having details of how the component should be processed, instantiated and used at
runtime.
Structural Directives
A structure directive basically deals with manipulating the dom elements. Structural directives have a * sign
before the directive. For example, *ngIf and *ngFor.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 37/88
6/13/2019 Angular 6 Quick Guide
Attribute Directives
Attribute directives deal with changing the look and behavior of the dom element. You can create your own
directives as shown below.
Let us see how to create the custom directive. We will create the directive using the command line. The command
to create the directive using the command line is −
ng g directive nameofthedirective
e.g
ng g directive changeText
The above files, i.e., change-text.directive.spec.ts and change-text.directive.ts get created and the
app.module.ts file is updated.
app.module.ts
The ChangeTextDirective class is included in the declarations in the above file. The class is also imported from
the file given below.
change-text. directive
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 38/88
6/13/2019 Angular 6 Quick Guide
The above file has a directive and it also has a selector property. Whatever we define in the selector, the same has
to match in the view, where we assign the custom directive.
change-text.directive.ts
In the above file, there is a class called ChangeTextDirective and a constructor, which takes the element of type
ElementRef, which is mandatory. The element has all the details to which the Change Text directive is applied.
We have added the console.log element. The output of the same can be seen in the browser console. The text of
the element is also changed as shown above.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 39/88
6/13/2019 Angular 6 Quick Guide
ANGULAR 6 - PIPES
In this chapter, we will discuss what are Pipes in Angular 6. Pipes were earlier called filters in ANGULAR1 and called
pipes in Angular 2 onwards.
The | character is used to transform data. Following is the syntax for the same
It takes integers, strings, arrays, and date as input separated with | to be converted in the format as required and
display the same in the browser.
Here, we want to display the text given to uppercase. This can be done using pipes as follows −
app.component.ts
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 40/88
6/13/2019 Angular 6 Quick Guide
<b>{{title | uppercase}}</b><br/>
<b>{{title | lowercase}}</b>
Angular 6 provides some built-in pipes. The pipes are listed below −
Lowercasepipe
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 41/88
6/13/2019 Angular 6 Quick Guide
Uppercasepipe
Datepipe
Currencypipe
Jsonpipe
Percentpipe
Decimalpipe
Slicepipe
We have already seen the lowercase and uppercase pipes. Let us now see how the other pipes work.
The following line of code will help us define the required variables in app.component.ts file −
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 42/88
6/13/2019 Angular 6 Quick Guide
<h1>Slice Pipe</h1>
<b>{{months | slice:2:6}}</b>
// here 2 and 6 refers to the start and the end index
</div>
</div>
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 43/88
6/13/2019 Angular 6 Quick Guide
app.sqrt.ts
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 44/88
6/13/2019 Angular 6 Quick Guide
To create a custom pipe, we have to import Pipe and Pipe Transform from Angular/core. In the @Pipe directive,
we have to give the name to our pipe, which will be used in our .html file. Since, we are creating the sqrt pipe, we
will name it sqrt.
As we proceed further, we have to create the class and the class name is SqrtPipe. This class will implement the
PipeTransform.
The transform method defined in the class will take argument as the number and will return the number after
taking the square root.
Since we have created a new file, we need to add the same in app.module.ts. This is done as follows −
We have created the app.sqrt.ts class. We have to import the same in app.module.ts and specify the path of
the file. It also has to be included in the declarations as shown above.
Let us now see the call made to the sqrt pipe in the app.component.html file.
<h1>Custom Pipe</h1>
<b>Square root of 25 is: {{25 | sqrt}}</b>
<br/>
<b>Square root of 729 is: {{729 | sqrt}}</b>
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 45/88
6/13/2019 Angular 6 Quick Guide
ANGULAR 6 - ROUTING
Routing basically means navigating between pages. You have seen many sites with links that direct you to a new
page. This can be achieved using routing. Here the pages that we are referring to will be in the form of
components. We have already seen how to create a component. Let us now create a component and see how to use
routing with it.
In the main parent component app.module.ts, we have to now include the router module as shown below −
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 46/88
6/13/2019 Angular 6 Quick Guide
path: 'new-cmp',
component: NewCmpComponent
}
])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Here, the RouterModule is imported from angular/router. The module is included in the imports as shown below
−
RouterModule.forRoot([
{
path: 'new-cmp',
component: NewCmpComponent
}
])
RouterModule refers to the forRoot which takes an input as an array, which in turn has the object of the path
and the component. Path is the name of the router and component is the name of the class, i.e., the component
created.
New-cmp.component.ts
New-cmp.component.html
<p>
{{newcomponent}}
</p>
<p>
new-cmp works!
</p>
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 47/88
6/13/2019 Angular 6 Quick Guide
Now, we need the above content from the html file to be displayed whenever required or clicked from the main
module. For this, we need to add the router details in the app.component.html.
<h1>Custom Pipe</h1>
<b>Square root of 25 is: {{25 | sqrt}}</b><br/>
<b>Square root of 729 is: {{729 | sqrt}}</b>
<br />
<br />
<br />
<a routerLink = "new-cmp">New component</a>
<br />
<br/>
<router-outlet></router-outlet>
In the above code, we have created the anchor link tag and given routerLink as "new-cmp". This is referred in
app.module.ts as the path.
When a user clicks new component, the page should display the content. For this, we need the following tag -
<router-outlet> </router-outlet>.
The above tag ensures that the content in the new-cmp.component.html will be displayed on the page when a
user clicks new component.
When a user clicks New component, you will see the following in the browser.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 48/88
6/13/2019 Angular 6 Quick Guide
The url contains HTTP://LOCALHOST:4200/NEW-CMP. Here, the new-cmp gets appended to the original url,
which is the path given in the app.module.ts and the router-link in the app.component.html.
When a user clicks New component, the page is not refreshed and the contents are shown to the user without any
reloading. Only a particular piece of the site code will be reloaded when clicked. This feature helps when we have
heavy content on the page and needs to be loaded based on the user interaction. The feature also gives a good user
experience as the page is not reloaded.
ANGULAR 6 - SERVICES
In this chapter, we will discuss the services in Angular 6.
We might come across a situation where we need some code to be used everywhere on the page. It can be for data
connection that needs to be shared across components, etc. Services help us achieve that. With services, we can
access methods and properties across other components in the entire project.
To create a service, we need to make use of the command line. The command for the same is −
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 49/88
6/13/2019 Angular 6 Quick Guide
Following are the files created at the bottom - myservice.service.specs.ts and myservice.service.ts.
myservice.service.ts
Here, the Injectable module is imported from the @angular/core. It contains the @Injectable method and a
class called MyserviceService. We will create our service function in this class.
Before creating a new service, we need to include the service created in the main parent app.module.ts.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 50/88
6/13/2019 Angular 6 Quick Guide
@NgModule({
declarations: [
SqrtPipe,
AppComponent,
NewCmpComponent,
ChangeTextDirective
],
imports: [
BrowserModule,
RouterModule.forRoot([
{
path: 'new-cmp',
component: NewCmpComponent
}
])
],
providers: [MyserviceService],
bootstrap: [AppComponent]
})
export class AppModule { }
We have imported the Service with the class name and the same class is used in the providers. Let us now switch
back to the service class and create a service function.
In the service class, we will create a function which will display today’s date. We can use the same function in the
main parent component app.component.ts and also in the new component new-cmp.component.ts that we
created in the previous chapter.
Let us now see how the function looks in the service and how to use it in components.
In the above service file, we have created a function showTodayDate. Now we will return the new Date created.
Let us see how we can access this function in the component class.
app.component.ts
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 51/88
6/13/2019 Angular 6 Quick Guide
The ngOnInit function gets called by default in any component created. The date is fetched from the service as
shown above. To fetch more details of the service, we need to first include the service in the component ts file.
{{todaydate}}
<app-new-cmp></app-new-cmp>
// data to be displayed to user from the new component class.
Let us now see how to use the service in the new component created.
In the new component that we have created, we need to first import the service that we want and access the
methods and properties of the same. Please see the code highlighted. The todaydate is displayed in the component
html as follows −
<p>
{{newcomponent}}
</p>
<p>
Today's Date : {{todaydate}}
</p>
The selector of the new component is used in the app.component.html file. The contents from the above html
file will be displayed in the browser as shown below −
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 52/88
6/13/2019 Angular 6 Quick Guide
If you change the property of the service in any component, the same is changed in other components too. Let us
now see how this works.
We will define one variable in the service and use it in the parent and the new component. We will again change
the property in the parent component and will see if the same is changed in the new component or not.
In myservice.service.ts, we have created a property and used the same in other parent and new component.
Let us now use the serviceproperty variable in other components. In app.component.ts, we are accessing the
variable as follows −
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 53/88
6/13/2019 Angular 6 Quick Guide
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 4 Project!';
todaydate;
componentproperty;
constructor(private myservice: MyserviceService) {}
ngOnInit() {
this.todaydate = this.myservice.showTodayDate();
console.log(this.myservice.serviceproperty);
this.myservice.serviceproperty = "component created"; // value is changed.
this.componentproperty = this.myservice.serviceproperty;
}
}
We will now fetch the variable and work on the console.log. In the next line, we will change the value of the
variable to "component created". We will do the same in new-cmp.component.ts.
In the above component, we are not changing anything but directly assigning the property to the component
property.
Now when you execute it in the browser, the service property will be changed since the value of it is changed in
app.component.ts and the same will be displayed for the new-cmp.component.ts.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 54/88
6/13/2019 Angular 6 Quick Guide
To start using the http service, we need to import the module in app.module.ts as shown below −
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 55/88
6/13/2019 Angular 6 Quick Guide
})
export class AppModule { }
If you see the highlighted code, we have imported the HttpModule from @angular/http and the same is also
added in the imports array.
Let us understand the code highlighted above. We need to import http to make use of the service, which is done as
follows −
In the class AppComponent, a constructor is created and the private variable http of type Http. To fetch the
data, we need to use the get API available with http as follows
this.http.get();
We will use the test url − https://jsonplaceholder.typicode.com/users to fetch the json data. Two operations are
performed on the fetched url data map and subscribe. The Map method helps to convert the data to json format.
To use the map, we need to import the same as shown below −
Once the map is done, the subscribe will log the output in the console as shown in the browser −
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 56/88
6/13/2019 Angular 6 Quick Guide
If you see, the json objects are displayed in the console. The objects can be displayed in the browser too.
For the objects to be displayed in the browser, update the codes in app.component.html and
app.component.ts as follows −
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 57/88
6/13/2019 Angular 6 Quick Guide
In app.component.ts, using the subscribe method we will call the display data method and pass the data
fetched as the parameter to it.
In the display data method, we will store the data in a variable httpdata. The data is displayed in the browser
using for over this httpdata variable, which is done in the app.component.html file.
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "[email protected]",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
The object has properties such as id, name, username, email, and address that internally has street, city, etc. and
other details related to phone, website, and company. Using the for loop, we will display the name and the city
details in the browser as shown in the app.component.html file.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 58/88
6/13/2019 Angular 6 Quick Guide
Let us now add the search parameter, which will filter based on specific data. We need to fetch the data based on
the search param passed.
app.component.ts
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 59/88
6/13/2019 Angular 6 Quick Guide
}
displaydata(data) {this.httpdata = data;}
}
For the get api, we will add the search param id = this.searchparam. The searchparam is equal to 2. We need the
details of id = 2 from the json file.
We have consoled the data in the browser, which is received from the http. The same is displayed in the browser
console. The name from the json with id = 2 is displayed in the browser.
To start using the http service, we need to import the module in app.module.ts as shown below −
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 60/88
6/13/2019 Angular 6 Quick Guide
If you see the highlighted code, we have imported the HttpClientModule from @angular/common/http and the
same is also added in the imports array.
Let us understand the code highlighted above. We need to import http to make use of the service, which is done as
follows −
In the class AppComponent, a constructor is created and the private variable http of type Http. To fetch the
data, we need to use the get API available with http as follows
this.http.get();
We will use the test url − https://jsonplaceholder.typicode.com/users to fetch the json data. The subscribe will log
the output in the console as shown in the browser −
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 61/88
6/13/2019 Angular 6 Quick Guide
If you see, the json objects are displayed in the console. The objects can be displayed in the browser too.
For the objects to be displayed in the browser, update the codes in app.component.html and
app.component.ts as follows −
In app.component.ts, using the subscribe method we will call the display data method and pass the data
fetched as the parameter to it.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 62/88
6/13/2019 Angular 6 Quick Guide
In the display data method, we will store the data in a variable httpdata. The data is displayed in the browser
using for over this httpdata variable, which is done in the app.component.html file.
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "[email protected]",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
The object has properties such as id, name, username, email, and address that internally has street, city, etc. and
other details related to phone, website, and company. Using the for loop, we will display the name and the city
details in the browser as shown in the app.component.html file.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 63/88
6/13/2019 Angular 6 Quick Guide
Let us now add the search parameter, which will filter based on specific data. We need to fetch the data based on
the search param passed.
app.component.ts
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 64/88
6/13/2019 Angular 6 Quick Guide
For the get api, we will add the search param id = this.searchparam. The searchparam is equal to 2. We need the
details of id = 2 from the json file.
We have consoled the data in the browser, which is received from the http. The same is displayed in the browser
console. The name from the json with id = 2 is displayed in the browser.
ANGULAR 6 - FORMS
In this chapter, we will see how forms are used in Angular 6. We will discuss two ways of working with forms -
template driven form and model driven forms.
Let us now consider working on the Template driven form. We will create a simple login form and add the email
id, password and submit the button in the form. To start with, we need to import to FormsModule from
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 65/88
6/13/2019 Angular 6 Quick Guide
So in app.module.ts, we have imported the FormsModule and the same is added in the imports array as shown
in the highlighted code.
We have created a simple form with input tags having email id, password and the submit button. We have
assigned type, name, and placeholder to it.
In template driven forms, we need to create the model form controls by adding the ngModel directive and the
name attribute. Thus, wherever we want Angular to access our data from forms, add ngModel to that tag as
shown above. Now, if we have to read the emailid and passwd, we need to add the ngModel across it.
If you see, we have also added the ngForm to the #userlogin. The ngForm directive needs to be added to the
form template that we have created. We have also added function onClickSubmit and assigned
userlogin.value to it.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 66/88
6/13/2019 Angular 6 Quick Guide
Let us now create the function in the app.component.ts and fetch the values entered in the form.
In the above app.component.ts file, we have defined the function onClickSubmit. When you click on the form
submit button, the control will come to the above function.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 67/88
6/13/2019 Angular 6 Quick Guide
The form looks like as shown below. Let us enter the data in it and in the submit function, the email id is already
entered.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 68/88
6/13/2019 Angular 6 Quick Guide
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 69/88
6/13/2019 Angular 6 Quick Guide
],
imports: [
BrowserModule,
HttpModule,
ReactiveFormsModule,
RouterModule.forRoot([
{
path: 'new-cmp',
component: NewCmpComponent
}
])
],
providers: [MyserviceService],
bootstrap: [AppComponent]
})
export class AppModule { }
In app.component.ts, we need to import a few modules for the model driven form. For example, import {
FormGroup, FormControl } from '@angular/forms'.
The variable formdata is initialized at the start of the class and the same is initialized with FormGroup as shown
above. The variables emailid and passwd are initialized with default values to be displayed in the form. You can
keep it blank in case you want to.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 70/88
6/13/2019 Angular 6 Quick Guide
We have used formdata to initialize the form values; we need to use the same in the form UI
app.component.html.
<div>
<form [formGroup] = "formdata" (ngSubmit) = "onClickSubmit(formdata.value)" >
<input type = "text" class = "fortextbox" name = "emailid" placeholder = "emailid"
formControlName="emailid">
<br/>
In the .html file, we have used formGroup in square bracket for the form; for example, [formGroup]="formdata".
On submit, the function is called onClickSubmit for which formdata.value is passed.
The input tag formControlName is used. It is given a value that we have used in the app.component.ts file.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 71/88
6/13/2019 Angular 6 Quick Guide
On clicking submit, the control will pass to the function onClickSubmit, which is defined in the
app.component.ts file.
On clicking Login, the value will be displayed as shown in the above screenshot.
Form Validation
Let us now discuss form validation using model driven form. You can use the built-in form validation or also use
the custom validation approach. We will use both the approaches in the form. We will continue with the same
example that we created in one of our previous sections. With Angular 4, we need to import Validators from
@angular/forms as shown below −
Angular has built-in validators such as mandatory field, minlength, maxlength, and pattern. These are to
be accessed using the Validators module.
You can just add validators or an array of validators required to tell Angular if a particular field is mandatory.
Let us now try the same on one of the input textboxes, i.e., email id. For the email id, we have added the following
validation parameters −
Required
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 72/88
6/13/2019 Angular 6 Quick Guide
Pattern matching
In Validators.compose, you can add the list of things you want to validate on the input field. Right now, we
have added the required and the pattern matching parameters to take only valid email.
In the app.component.html, the submit button is disabled if any of the form inputs are not valid. This is done
as follows −
<div>
<form [formGroup] = "formdata" (ngSubmit) = "onClickSubmit(formdata.value)" >
<input type = "text" class = "fortextbox" name = "emailid" placeholder = "emailid"
formControlName = "emailid">
<br/>
<input type = "password" class = "fortextbox" name = "passwd"
placeholder = "passwd" formControlName = "passwd">
<br/>
<input type = "submit" [disabled] = "!formdata.valid" class = "forsubmit"
value = "Log In">
</form>
</div>
<p>
Email entered is : {{emailid}}
</p>
For the submit button, we have added disabled in the square bracket, which is given value - !formdata.valid.
Thus, if the formdata.valid is not valid, the button will remain disabled and the user will not be able to submit it.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 73/88
6/13/2019 Angular 6 Quick Guide
In the above case, the email id entered is invalid, hence the login button is disabled. Let us now try entering the
valid email id and see the difference.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 74/88
6/13/2019 Angular 6 Quick Guide
Now, the email id entered is valid. Thus, we can see the login button is enabled and the user will be able to submit
it. With this, the email id entered is displayed at the bottom.
Let us now try custom validation with the same form. For custom validation, we can define our own custom
function and add the required details in it. We will now see an example for the same.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 75/88
6/13/2019 Angular 6 Quick Guide
In the above example, we have created a function password validation and the same is used in a previous
section in the formcontrol − passwd: new FormControl"", this. passwordvalidation.
In the function that we have created, we will check if the length of the characters entered is appropriate. If the
characters are less than five, it will return with the passwd true as shown above - return {"passwd" : true};. If
the characters are more than five, it will consider it as valid and the login will be enabled.
We have entered only three characters in the password and the login is disabled. To enable login, we need more
than five characters. Let us now enter a valid length of characters and check.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 76/88
6/13/2019 Angular 6 Quick Guide
The login is enabled as both the email id and the password are valid. The email is displayed at the bottom as we
log in.
ANGULAR 6 - ANIMATIONS
Animations add a lot of interaction between the html elements. Animation was also available with ANGULAR2. The
difference with Angular 6 is that animation is no more a part of the @angular/core library, but is a separate
package that needs to be imported in app.module.ts.
The BrowserAnimationsModule needs to be added to the import array in app.module.ts as shown below −
app.module.ts
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 77/88
6/13/2019 Angular 6 Quick Guide
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<div>
<button (click) = "animate()">Click Me</button>
<div [@myanimation] = "state" class = "rotate">
<img src = "assets/images/img.png" width = "100" height = "100">
</div>
</div>
For the main div, we have added a button and a div with an image. There is a click event for which the animate
function is called. And for the div, the @myanimation directive is added and given the value as state.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 78/88
6/13/2019 Angular 6 Quick Guide
We have to import the animation function that is to be used in the .ts file as shown above.
Here we have imported trigger, state, style, transition, and animate from @angular/animations.
animations: [
trigger('myanimation',[
state('smaller',style({
transform : 'translateY(100px)'
})),
state('larger',style({
transform : 'translateY(0px)'
})),
transition('smaller <=> larger',animate('300ms ease-in'))
])
]
Trigger defines the start of the animation. The first param to it is the name of the animation to be given to the
html tag to which the animation needs to be applied. The second param are the functions we have imported -
state, transition, etc.
The state function involves the animation steps, which the element will transition between. Right now we have
defined two states, smaller and larger. For smaller state, we have given the style transform:translateY100px
and transform:translateY100px.
Transition function adds animation to the html element. The first argument takes the states, i.e., start and end;
the second argument accepts the animate function. The animate function allows you to define the length, delay,
and easing of a transition.
Let us now see the .html file to see how the transition function works
<div>
<button (click) = "animate()">Click Me</button>
<div [@myanimation] = "state" class="rotate">
<img src = "assets/images/img.png" width = "100" height = "100">
</div>
</div>
There is a style property added in the @component directive, which centrally aligns the div. Let us consider the
following example to understand the same −
styles:[`
div{
margin: 0 auto;
text-align: center;
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 79/88
6/13/2019 Angular 6 Quick Guide
width:200px;
}
.rotate{
width:100px;
height:100px;
border:solid 1px red;
}
`],
Here, a special character [``] is used to add styles to the html element, if any. For the div, we have given the
animation name defined in the app.component.ts file.
On the click of a button it calls the animate function, which is defined in the app.component.ts file as follows −
The state variable is defined and is given the default value as smaller. The animate function changes the state on
click. If the state is larger, it will convert to smaller; and if smaller, it will convert to larger.
This is how the output in the browser (HTTP://LOCALHOST:4200/) will look like −
Upon clicking the Click Me button, the position of the image is changed as shown in the following screenshot −
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 80/88
6/13/2019 Angular 6 Quick Guide
The transform function is applied in the y direction, which is changed from 0 to 100PX when the Click Me button
is clicked. The image is stored in the assets/images folder.
ANGULAR 6 - MATERIALS
Materials offer a lot of built-in modules for your project. Features such as autocomplete, datepicker, slider,
menus, grids, and toolbar are available for use with materials in Angular 6.
To use materials, we need to import the package. Angular 2 also has all the above features but they are available as
part of the @angular/core module. Angular 6 has come up with a separate module @angular/materials.. This
helps the user to import the required materials.
To start using materials, you need to install two packages - materials and cdk. Material components depend on
the animation module for advanced features, hence you need the animation package for the same, i.e.,
@angular/animations. The package has already been updated in the previous chapter.
Let us now see the package.json. @angular/material and @angular/cdk are installed.
{
"name": "angular6-app",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true, "dependencies": {
"@angular/animations": "^6.1.0",
"@angular/cdk": "^6.4.7",
"@angular/common": "^6.1.0",
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 81/88
6/13/2019 Angular 6 Quick Guide
"@angular/compiler": "^6.1.0",
"@angular/core": "^6.1.0",
"@angular/forms": "^6.1.0",
"@angular/http": "^6.1.0",
"@angular/material": "^6.4.7",
"@angular/platform-browser": "^6.1.0",
"@angular/platform-browser-dynamic": "^6.1.0",
"@angular/router": "^6.1.0",
"core-js": "^2.5.4",
"rxjs": "^6.0.0",
"zone.js": "~0.8.26"
},
"devDependencies": {
"@angular-devkit/build-angular": "~0.7.0",
"@angular/cli": "~6.1.3",
"@angular/compiler-cli": "^6.1.0",
"@angular/language-service": "^6.1.0",
"@types/jasmine": "~2.8.6",
"@types/jasminewd2": "~2.0.3",
"@types/node": "~8.9.4",
"codelyzer": "~4.2.1",
"jasmine-core": "~2.99.1",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~1.7.1",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~2.0.0",
"karma-jasmine": "~1.1.1",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.3.0",
"ts-node": "~5.0.1",
"tslint": "~5.9.1",
"typescript": "~2.7.2"
}
}
We have highlighted the packages that are installed to work with materials.
We will now import the modules in the parent module − app.module.ts as shown below.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 82/88
6/13/2019 Angular 6 Quick Guide
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
In the above file, we have imported the following modules from @angular/materials.
imports: [
BrowserModule,
BrowserAnimationsModule,
MatButtonModule,
MatMenuModule,
FormsModule,
MatSidenavModule
]
@import "~@angular/material/prebuilt-themes/indigo-pink.css";
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 83/88
6/13/2019 Angular 6 Quick Guide
Menu
To add menu, <mat-menu></mat-menu> is used. The file and Save As items are added to the button under
mat-menu. There is a main button added Menu. The reference of the same is given the <mat-menu> by using
[matMenuTriggerFor]="menu" and using the menu with # in <mat-menu>.
SideNav
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 84/88
6/13/2019 Angular 6 Quick Guide
Upon clicking Menu, you will get two items File and Save As as shown below −
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 85/88
6/13/2019 Angular 6 Quick Guide
Let us now add a datepicker using materials. To add a datepicker, we need to import the modules required to
show the datepicker.
In app.module.ts, we have imported the following module as shown below for datepicker.
<mat-form-field>
<input matInput [matDatepicker] = "picker" placeholder = "Choose a date">
<mat-datepicker-toggle matSuffix [for] = "picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 86/88
6/13/2019 Angular 6 Quick Guide
ANGULAR 6 - CLI
Angular CLI makes it easy to start with any Angular project. Angular CLI comes with commands that help us
create and start on our project very fast. Let us now go through the commands available to create a project, a
component and services, change the port, etc.
To work with Angular CLI, we need to have it installed on our system. Let us use the following command for the
same −
To create a new project, we can run the following command in the command line and the project will be created.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 87/88
6/13/2019 Angular 6 Quick Guide
ng new PROJECT-NAME
cd PROJECT-NAME
ng serve //
ng serve // will compile and you can see the output of your project in the browser −
http://localhost:4200/
4200 is the default port used when a new project is created. You can change the port with the following command
−
The following table lists down a few important commands required while working with Angular 4 projects.
Whenever a new module, a component, or a service is created, the reference of the same is updated in the parent
module app.module.ts.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 88/88