tag:blogger.com,1999:blog-46727214409899238452024-03-24T16:32:11.623-07:00AngularBytesAngularBytes is an online magazine dedicated to Angular developers. The idea is to make varieties of Angular development tutorials, blogs, tips, tricks, source code and tools available to Angular developers. Angular is a complete and emerging framework for front end development. Join us and code your bytes in AngularBytes.Witspry Technovatehttp://www.blogger.com/profile/13599435720165810309noreply@blogger.comBlogger16125tag:blogger.com,1999:blog-4672721440989923845.post-88667568526797238682017-10-25T12:40:00.001-07:002019-01-09T00:18:05.834-08:00A Complete Angular 5 Tutorial<div dir="ltr" style="text-align: left;" trbidi="on">
<img class="img img-responsive center-block" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEia_bqM0SuT4pTaQ7fcHVLhm_djVO8_7Ok3AbRMy_3HLj9T3wVykUnlyH3ZRKDnkL87tXOFdVe-oI4gcAqKqC5QfPZvh7uHqst6Mqx77P1wGqWvRbga-VEh9JMFB2L0U2DHyGQ6FYTjl1cd/s640/a+complete+angular+tutorial.JPG" />
<br/>
<p> <strong>Important announcement</strong> : We are moving all our content to new website - <a href="https://witscad.com/courses"> Witscad Courses </a>. Feel free to visit. </p>
<br/>
<p>Find updated complete Angular course here - <a href="https://witscad.com/course/complete-angular-tutorial"> Complete Angular 7 course </a> </p>
<br/>
<strong>Angular is Awesome!</strong> Angular developers know that. This a complete Angular 5 tutorial covering all important features that you will be needing for a complete Angular end to end development.
<br />
<br />
If anyone has not yet started working with Angular, there is no issue. You can kick start with the first chapter - <a href="https://angularbytes.witspry.com/2017/10/an-introduction-to-angular-getting-started-architecture-and-components.html" target="_blank"> An Introduction to Angular </a> which will make to ready to develop with Angular and any of its ongoing versions.
<br />
<br />
This tutorial is divided into 11 parts. The first part is specially for beginners who never worked with Angular. The second part defines the new features of Angular 5. The next 9 parts explains each feature of Angular.
<br />
<br />
At the end of the each part, a link is mentioned where you can see the live running code on plunkr and learn the code very easily. Each of these live code is based on the latest angular version - Angular 5. Feel free to fork the source code from plunkr.
<br />
<br />
I believe at the end of this course, you will feel comfortable and ready to develop with Angular. Let's start. Click on links provided below in the table of contents to read each chapter of this course.
<br />
<br />
<h2>
Table of Contents</h2>
<div style="font-size:14pt;">
<ol>
<li>
<a href="https://angularbytes.witspry.com/2017/10/an-introduction-to-angular-getting-started-architecture-and-components.html" target="_blank">
An Introduction to Angular : Getting started, Architecture and Components
</a>
</li>
<li>
<a href="https://angularbytes.witspry.com/2017/10/whats-new-in-angular-5-features-and-improvements.html" target="_blank">
Whats new in Angular 5
</a>
</li>
<li>
<a href="http://angularbytes.witspry.com/2017/09/angular-5-data-and-event-bindings.html" target="_blank">
Data and Event Bindings
</a>
</li>
<li>
<a href="http://angularbytes.witspry.com/2017/09/angular-5-builtin-async-and-custom-pipes.html" target="_blank">
Using the builtin async and custom pipes
</a>
</li>
<li>
<a href="http://angularbytes.witspry.com/2017/09/angular-5-working-with-nested-components.html" target="_blank">
Working with nested components
</a>
</li>
<li>
<a href="http://angularbytes.witspry.com/2017/09/angular-5-services-and-dependency-injection.html" target="_blank">
Services and Dependency Injection
</a>
</li>
<li>
<a href="http://angularbytes.witspry.com/2017/09/angular-5-life-cycle-hooks.html" target="_blank">
Life cycle hooks
</a>
</li>
<li>
<a href="http://angularbytes.witspry.com/2017/09/angular-5-consuming-restful-service-with-httpclient-rxjs.html" target="_blank">
Consuming restful services with HTTPClient and RxJS
</a>
</li>
<li>
<a href="http://angularbytes.witspry.com/2017/09/angular-5-routing-and-navigation.html" target="_blank">
Routing and Navigation
</a>
</li>
<li>
<a href="https://angularbytes.witspry.com/2017/10/angular-5-module-and-feature-modules.html" target="_blank">
Angular Modules and Feature Modules
</a>
</li>
<li>
<a href="https://angularbytes.witspry.com/2017/10/angular-5-cli.html" target="_blank">
Angule CLI (Command Line Interface)
</a>
</li>
</ol>
</div>
</div>
Satya Jugranhttp://www.blogger.com/profile/02579918194785863102noreply@blogger.com4tag:blogger.com,1999:blog-4672721440989923845.post-58619202072319721792017-10-25T07:49:00.000-07:002019-01-10T05:32:38.313-08:00An Introduction to Angular : Getting started, Architecture and Components<div dir="ltr" style="text-align: left;" trbidi="on">
<img class="img img-responsive center-block" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjzLE5CshCK9eI3t95dzf79krsNpDS8FL6t9lqbwg0Wh56qHxK8O5ScwUbrDi1-ZIi8l91y68hk8HGl7avlgHa_irXEOyxCHNf-5ndbgzyEEGENCBKva2JlE7BuXei6G-dN8aeAgxFVoDYq/s640/introduction-to-angular.JPG" />
<br/>
<p> <strong>Important announcement</strong> : We are moving all our content to new website - <a href="https://witscad.com/courses"> Witscad Courses </a>. You can find the updated Angular course here - <a href="https://witscad.com/course/complete-angular-tutorial">A Complete Angular Tutorial</a>. Feel free to visit. </p>
<h2>
What is Angular?</h2>
Angular is a complete framework for building client application or primarily browser based applications. Angular allows us to write client application in Component Based Design Pattern. It offers us to write both in Javascript and Typescript, however it majorly prefers TypeScript.
<br /><br/>
So, now you know with Angular we build browser based applications. To explain this further let's first understand the thought process around Angular.
<br /><br/>
<h2>
Component Design - The Angular's way of developing an application</h2>
A client/browser application can be simply build using <em>HTML</em>, <em>CSS</em> and <em>Javascript</em>. Problem occurs when the application starts growing it becomes hard and hard to maintain and incorporating/integrating changes.
<br /><br/>
Angular solves this problem by providing a <strong>Component Based Design Pattern</strong>. This is a pattern where we first figure out various components of the application, take each component in centre and build application around it.
<br /><br/>
The benefit of using <strong>Component Based Design</strong> is the we can reuse different components at different places in our application. A Component can be a small or big part of the application. A Component can contain other components.
<br/><br/>
A Component design approach is very useful from <strong>UI/UX</strong> perspective because if we see things in real world we realize that those are individual entities or are made up of some other entities. For e.g. an air conditioner consists of a fan, a condenser, electric assemblies etc. So, an AC is also a Component which we fit in our home (app) and it is made up of several other components.
<br /><br/>
Now since I took a real world example, the question arises that what is the difference between Component Based Design and Object Oriented Design. This is very important to understand.
<br /><br/>
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Post body ad responsive -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-4262325767595391" data-ad-format="auto" data-ad-slot="9970526860" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br/><br/>
<h3>Object Oriented Design v/s Component Based Design</h3>
In context of building client/browser based application, the <u>Object Oriented Design</u> is all about writing model classes and providing functionality to them. This we usually achieve be making classes and objects javascript only and use this over html and css.
<br /><br/>
<img class="img img-responsive center-block" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEisvjj1E6Ms6Odlqba7v9iHs-CtGgVIi0brM4pXD4JUCgKuxNIKeBjG1IPcmVkcifiLwkldRmOjtItoeyp6E0xTIQtdfO3yOnmWQJc5DFN2kUNRC7J54akXylfMGCARFc7p32bgkgb44fp6/s640/object+oriented+browser+development.jpg" />
<br /><br/>
In a <u>Component Based Design</u> we bother about creating a complete unit or piece which wraps HTML, CSS and Javascript together which will be enough to execute or display that unit. An application is a collection of components and a component can contain several other components.
<br /><br/>
<img class="img img-responsive center-block" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiGsOXlObmAmHOwxkPkX6gU2bbp99R-mgWLjtqk7SgxudRxXwU-NyGwfm6gnR7QTQuw7HV5JTWDwurDn_rczQfxYalU0yELYQ8M1baOmiPFpGDWVJZoTI-2QBXRw3EA6LaNRAgghKl1Cxir/s640/component+based+browser+development.jpg" />
<br /><br/>
<!-- Post body ad responsive -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-4262325767595391" data-ad-format="auto" data-ad-slot="9970526860" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br/><br/>
<h2>
How a Component in Angular looks like?</h2>
In Angular, we use to write component classes. Each Component class contains an HTML templates and logics to operate on that template.
<br /><br/>
<u>A typical Angular Component</u>
<br />
<div style="background: #ffffff; overflow:auto;width:auto;padding:.2em .6em;"><pre style="margin: 0; line-height: 125%"><span style="color: #008800; font-weight: bold">import</span> { Component } from <span >'@angular/core'</span>;
<span style="color: #008800; font-weight: bold">export</span> <span style="color: #008800; font-weight: bold">class</span> Player {
id: <span style="color: #333399; font-weight: bold">number</span>;
name: <span style="color: #333399; font-weight: bold">string</span>;
}
@Component({
selector<span style="color: #333333">:</span> <span >'my-app'</span>,
template<span style="color: #333333">:</span> <span >`
<span style="color: #007700"><h1></span>{{title}}<span style="color: #007700"></h1></span>
<span style="color: #007700"><h2></span>{{player.name}} details!<span style="color: #007700"></h2></span>
<span style="color: #007700"><div><label></span>id: <span style="color: #007700"></label></span>{{player.id}}<span style="color: #007700"></div></span>
<span style="color: #007700"><div></span>
<span style="color: #007700"><label></span>name: <span style="color: #007700"></label></span>
<span style="color: #007700"><input</span> <span style="color: #0000CC">[(ngModel)]=</span><span >"player.name"</span> <span style="color: #0000CC">placeholder=</span><span >"name"</span><span style="color: #007700">></span>
<span style="color: #007700"></div></span>
`</span>
})
<span style="color: #008800; font-weight: bold">export</span> <span style="color: #008800; font-weight: bold">class</span> AppComponent {
title <span style="color: #333333">=</span> <span >'Chess Tournament'</span>;
player: <span style="color: #333399; font-weight: bold">Player</span> <span style="color: #333333">=</span> {
id: <span style="color: #333399; font-weight: bold">1</span>,
name<span style="color: #333333">:</span> <span >'Jeff'</span>
};
}
</pre></div>
<br />
As you can see there is a model class <em>Player</em> having two properties id and name. Also, there is one html template where some properties have been mentioned under different brackets. There is one <em>AppComponent</em> class where properties data has been assigned to them.
<br /><br/>
Don't worry about the code at this point of time, you will learn gradually as you will progress through this course.
<br /><br/>
<!-- Post body ad responsive -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-4262325767595391" data-ad-format="auto" data-ad-slot="9970526860" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br/><br/>
<h2>
Angular Architecture</h2>
<img class="img img-responsive center-block" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEixNuy5kLKyrlG1j5YK0nnutAcSzjx4ULh7OaTUcOV4HQVavmKAeZDp3-FEcm2xWvN5gvgJ4sxemWPNoIEnNIee8vYOaFdp12jZ-UiSPRfL4GxbGD6iS0ZZLsjyujVRK5KYRkVuUgXVe55X/s640/angular-architecture-credit-angular.png" />
<div class="text-center" style="width: 100%;">
Source and credits - angular.io</div>
<br /><br/>
A single unit of application in Angular is called <strong><a href="https://angularbytes.witspry.com/2017/10/angular-5-module-and-feature-modules.html" target="_blank">Module</a> </strong>. A module consists of different components, services and functions. Angular's own module is called <em>ngModule</em> which should be imported in the application before using Angular and its features.
<br /><br/>
Each Component class is associated with metadata. In the above example we have selector and template as a part of Angular metadata.
<br /><br/>
Angular also provides <a href="http://angularbytes.witspry.com/2017/09/angular-5-data-and-event-bindings.html target="_blank"">bindings</a> to bind component class property data to the template.
<br /><br/>
Angular's provides inbuilt and custom <a href="http://angularbytes.witspry.com/2017/09/angular-5-services-and-dependency-injection.html target="_blank"">services</a> that can be injected in any component to make use of service functionalities.
<br /><br/>
<div>So let's begin developing with Angular. </div>
<br />
<div class="text-center">Next <i class="fa fa-chevron-right"></i> <a href="http://angularbytes.witspry.com/2017/09/angular-5-data-and-event-bindings.html" target="_blank">
Data and Event Bindings
</a></div>
</div>
Satya Jugranhttp://www.blogger.com/profile/02579918194785863102noreply@blogger.com1tag:blogger.com,1999:blog-4672721440989923845.post-33701439728067123142017-10-20T00:51:00.000-07:002019-01-10T05:34:24.912-08:00Whats new in Angular 5 - Features and Improvements<div dir="ltr" style="text-align: left;" trbidi="on">
<img class="img img-responsive center-block" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhESrY6_JPafG1sJ6jzKNTLn5HaCpN1JiSX2AsGpO5hfQ4VcsTbyoCDc3KHtrnMJJfLrb0vz-yRFCRd9vFUDU3cYjPPkrypuNPd91UD_y6fYz5B-G_rkXOKEUX-eXQsDCwxJltC__eMI79v/s640/whats+new+in+Angular+5+-+new+features+and+improvements.JPG" />
<br />
<p> <strong>Important announcement</strong> : We are moving all our content to new website - <a href="https://witscad.com/courses"> Witscad Courses </a>. You can find the updated complete Angular course here - <a href="https://witscad.com/course/complete-angular-tutorial">A Complete Angular Tutorial</a>. Feel free to visit. </p>
<br/>
Angular developers know what Angular mean to the front end development. It's been an excitement for Angular developers as the wait is over with the arrival of Angular 5. Yeah!
<br />
<br />
The most important part that is the highlight of <strong>Angular 5</strong> is that there has been a lot and lot of bug fixes since Angular 4. This makes Angular 5 even more reliable.
<br />
<br />
These Angular 5 features and improvements is based on the Angular Github change logs collated from all Angular 5 beta and RC versions - <a href="https://github.com/angular/angular/blob/5.0.x/CHANGELOG.md" target="_blank">https://github.com/angular/angular/blob/5.0.x/CHANGELOG.md</a>
<br />
<br />
<div style="font-size: 14pt;">
So, here is the list of Angular 5 major features and performance improvements.</div>
<h2>
Native addEventListener for faster rendering</h2>
Angular 5 is now using the Javascript's native addEventListener method to register events. This gives a lot of performance improvement for a complex Angular applications where there are lots of event bindings.
<br />
<h2>
New Router hooks</h2>
<ul>
<li>Added <em>ActivationStart</em> and <em>ActivationEnd</em> router events </li>
<li>Two new Angular router hooks have been introduced to add event tracking activation of individual routes. These are <em>ChildActivationStart</em> and <em>ChildActivationEnd</em></li>
</ul>
<h2>
Invalid CSS properties detection</h2>
Angular 5 will now report errors in case it finds any discrepancies in the CSS while binding. This includes invalid CSS syntax and properties.
<br />
<h2>
Dropped use of the Intl API from @angular/common</h2>
The Intl API from <em>@angular/common</em> has been removed to improve browser support. Intl API is not needed anymore, we extract and use data from <em>Common Locale Data Repository (CLDR)</em> instead.
<br />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Post body ad responsive -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-4262325767595391" data-ad-format="auto" data-ad-slot="9970526860" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br/>
<h2>
Angular Pipes changes</h2>
<h3>
Date pipe changes</h3>
A new optional parameter - <strong>timezone</strong> that lets you specify the timezone for a date (it will shift the date values based on the locale timezone so that you see it as it was from this other timezone).
<br />
<h3>
Plural/Decimal/Percent/Currency pipe changes</h3>
In all Plural, Decimal, Percent and Currency pipe a new optional parameter <strong>locale</strong> has been introduced that lets you use a specific locale for this pipe (instead of using the default LOCALE_ID)
<br />
<h2>
New Forms feature - updateOn for Performance Improvements </h2>
<strong>FormControls</strong>, <strong>FormGroups</strong>, and <strong>FormArrays</strong> now optionally accept an options object as their second argument. Validators and async validators can be passed in as part of this options object (though they can still be passed in as the second and third arg as before)
<br />
<br />
<div style="font-size: 14pt;">
There are three ways that are supported and can be used</div>
<br />
<ol>
<li>Add <em>updateOn</em> blur option to FormControls<br />
<div>
<ul>
<li>Add default updateOn values for groups and arrays </li>
<li>Add updateOn submit option to FormControls</li>
</ul>
By default, the value and validation status of a FormControl updates whenever its value changes. If an application has heavy validation requirements, updating on every text change can sometimes be too expensive.
This feature introduces a new option that improves performance by delaying form control updates until the "blur" event. To use it, set the updateOn option to blur when instantiating the FormControl.
<br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #008800; font-weight: bold;">const</span> c<span style="color: #333333;">=</span> <span style="color: #008800; font-weight: bold;">new</span> FormControl(<span style="background-color: #fff0f0;">''</span>, {
validators: <span style="color: #333399; font-weight: bold;">Validators.required</span>,
updateOn<span style="color: #333333;">:</span> <span style="background-color: #fff0f0;">'blur'</span>
});
</pre>
</div>
</div>
</li>
<li>Add <em>updateOn</em> support to <em>ngModelOptions</em> <br />
<div>
This introduces a new option to template-driven forms that improves performance by delaying form control updates until the "blur" or "submit" event. To use it, set the <strong>updateOn</strong> property in <strong>ngModelOptions</strong>.
<br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #007700;"><input</span> <span style="color: #0000cc;">ngModel</span> [<span style="color: #0000cc;">ngModelOptions</span>]="{<span style="color: #0000cc;">updateOn:</span> <span style="color: #0000cc;">blur</span>}"<span style="color: #007700;">></span>
</pre>
</div>
</div>
</li>
<li>Add <em>updateOn</em> and <em>ngFormOptions</em> to <em>NgForm</em> <br />
<div>
We have now a new Input property called <strong>ngFormOptions</strong> to the <strong>NgForm</strong> directive. You can use it to set default <strong>updateOn</strong> values for all the form's child controls. This default will be used unless the child has already explicitly set its own <strong>updateOn</strong> value in <strong>ngModelOptions</strong>.
<br />
Potential values: `change` | `blur` | `submit`
<br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #007700;"><form</span> [<span style="color: #0000cc;">ngFormOptions</span>]="{<span style="color: #0000cc;">updateOn:</span> <span style="color: #0000cc;">blur</span>}"<span style="color: #007700;">></span>
<span style="color: #007700;"><input</span> <span style="color: #0000cc;">name=</span><span style="background-color: #fff0f0;">"one"</span> <span style="color: #0000cc;">ngModel</span><span style="color: #007700;">></span> <span style="color: #888888;"><!-- will update on blur--></span>
<span style="color: #007700;"></form></span>
</pre>
</div>
</div>
</li>
</ol>
<h2>
Deprecate @angular/http</h2>
This is one major/breaking change that <em>@angular/http</em> is now deprecated in favor of <em>@angular/common/http</em>.
<br />
<h2>
Changes in @angular/platform-server</h2>
<ul>
<li>Provided a DOM implementation on the server </li>
<li>Uses Domino - <a href="https://github.com/fgnass/domino" target="_blank">https://github.com/fgnass/domino</a> and removes dependency on Parse5. With this change, platform-server also exposes a <strong>DOCUMENT</strong> and nativeElement that is closer to the client.</li>
<li>Users can provide a <strong>RENDER_MODULE_HOOK</strong> multi-provider that can insert/change document state just before it is rendered.</li>
<li>Added an API to transfer state from server : <strong>TransferState</strong> provides a shared store that is transferred from the server to client. To use it import <em>BrowserTransferStateModule</em> from the client app module and <em>ServerTransferStateModule</em> from the server app module.</li>
</ul>
<h2>
Changes in @angular/compiler</h2>
The Angular compiler now requires <strong>TypeScript 2.4.x</strong>. Apart from this few other changes have been introduced.
<br />
<ul>
<li>It allow multiple exportAs names.</li>
<li>Enabled strict checking of parameters to an @Injectable</li>
<li>Reuse the TypeScript typecheck for template typechecking</li>
</ul>
<br/>
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Post body ad responsive -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-4262325767595391" data-ad-format="auto" data-ad-slot="9970526860" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br/>
<h2>
New Angular package - @angular/service-worker </h2>
A new Angular package - <em>@angular/service-worker</em> has been introduced in Angular 5 release which wraps the major functionality of browser service workers. We can brief them as:
<br />
<strong>@angular/service-worker</strong> - a library for use within Angular client apps to communicate with the service worker.
<br />
<strong>@angular/service-worker/gen</strong> - a library for generating ngsw.json files from glob-based SW config files.
<br />
<strong>@angular/service-worker/ngsw-worker.js</strong> - the bundled service worker script itself.
<br />
<strong>@angular/service-worker/ngsw-cli.js</strong> - a CLI tool for generating ngsw.json files from glob-based SW config files.
<br />
<br />
<div>That's all folks! Feel free to mention any new Angular 5 features or any code samples in comments that is not mentioned here. We will add the same here with your attributions. </div></div>
Satya Jugranhttp://www.blogger.com/profile/02579918194785863102noreply@blogger.com3tag:blogger.com,1999:blog-4672721440989923845.post-90540335967069921032017-10-01T11:53:00.001-07:002019-01-10T05:35:02.418-08:00Angular 5 : CLI<div dir="ltr" style="text-align: left;" trbidi="on">
<img class="img img-responsive center-block" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgBhOdRYuyWacOJHJJtYUNkjjWsYp61PJPcV5KIy4P27JcxESlnX3lqZoFX1pn1CCxzO7SoOS9QLfkvJGCm2M26vHdzbmJtODN91KvRJjjBQBvAdUSmhSqEdolLioj_er3sE4BF8TGA4ukH/s640/angular-command-line-interface.png" />
<br/>
<p> <strong>Important announcement</strong> : We are moving all our content to new website - <a href="https://witscad.com/courses"> Witscad Courses </a>. You can find the updated complete Angular course here - <a href="https://witscad.com/course/complete-angular-tutorial">A Complete Angular Tutorial</a>. Feel free to visit. </p>
<strong>Angular CLI</strong> or Angular Command Line Interface is a set of tools that is used to initialize, develop, generate files, scaffold, test and maintain Angular application. To use this we need to install it first.
<br /><br/>
<div class="text-center"><strong>npm install -g @angular/cli</strong></div>
<br/>
It should be installed globally (with -g flag ). The CLI command name is <strong>"ng"</strong> which tells that we are going to execute an Angular command. The next we provide an Angular CLI command after ng e.g. ng <commandname>.
<br/>
Angular CLI provides us with various commands. If you want to see these commands then you can execute the CLI command - <strong>"ng help"</strong>. This will list out all the command that Angular CLI supports.
<br/>To check the version of CLI execute the command - <strong>"ng v"</strong>. This will show the angular version installed in a nice view.
</commandname><br />
<h2>
Angular CLI commands</h2>
<h3>
ng new</h3>
This is to create a new Angular project. This command automatically creates several other files necessary for project development, testing, configuration of our project. Moreover, it also installs the npm dependencies from package.json. Without much hassle, it makes it so easy to start an Angular project.
<br /><br/>
<img class="img img-responsive center-block" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhFf2hGpGLrk74QVvaTMGb8d34ECE8dYQX1Kz8WGUdI1I4pR_ueogzniObg2qLoLHLq_qj9fr-SD8-HLk6jQYv91iCX3c3sMjKP-0j2xAO0zLpyR3rJqXDrO4rs-g_6uA84mFXbVnroEEPi/s480/cli+ng+new.JPG" />
<br />
This command creates a folder structure with an index.html, favicon.ico, environment setting, karma and protractor configurations app component and a default app component.
<br /><br/>
<img class="img img-responsive center-block" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg7lpabm6jq2LJK9SXUQvrmGkMHOdQmNsIewAyVZy95BWh6fvhkFFTr8fSVYfPmtA5ikcKpNmf49DG5Ud8zweBK0JtHkegjfowsR5P9ZDFVo8hHqQoDS5Gl20VVt3gT3XMpKj09jxfHiPXg/s480/cli+ng+new+folder+structure.JPG" />
<br />
More options for this command can be found with - <strong>"ng new --help"</strong>
<br />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Post body ad responsive -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-4262325767595391" data-ad-format="auto" data-ad-slot="9970526860" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br/>
<h3>
ng serve</h3>
This command is used to build the application and start a web server. Lets execute this command in our welcome app.
<br /><br/>
<img class="img img-responsive center-block" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhR3scf2hY3EBEsmgtUVBhAw__S2npAvL-fiX4RrCTq5EGgkHnS8EuYGlar7htBaPqirLWLQvQ9qwK-AbEm7kPuNy8LeYWU2P-Xaavc1Jwd-2Dg1lSFkDsZ-RoynKl2Pp7hc0Ex4geU4sAm/s640/cli+ng+serve.JPG" />
<br />
And that's how it looks in the browser
<br /><br/>
<img class="img img-responsive center-block" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiRNX4ysFoAwswMeOqzS4kNh3RyNwYgupJmi9cqXs3irO6y6AGiMPKR10t5AM2DYRFcH2y1LT9vz_XleTaRjcO-BU8mC3UTn1-7S15Xqvch7iYxYXQozt7uoPplvEInnJZpylPD2Y0G7TPp/s480/cli+ng+serve+browser.JPG" />
<br />
<h4>
ng serve switches</h4>
To build and open in browser together use command - <strong>"ng serve -o"</strong>
<br />
To work in watch mode use flag "-w". This will watch for your code changes and simultaneously keep building the app.
If you want to refresh your browser every time you change your source code, then use flag <strong>"-lr"</strong> or <strong>"--live-reload"</strong>
<br />
CLI runs the app with default port of "4200". To work on some different port use flag <strong>"-p <port-number>"</port-number></strong>
<br />
<h3>
ng generate</h3>
This command is used to generate specific blueprints. We can generate the following blueprints
<br />
class / component / directive / enum / guard / interface / module / pipe / service
<br />
To generate a component blueprint, use <strong>"ng generate component <class name="">"</class></strong>. Let us create a component <strong>"home"</strong> in our welcome app.
<br /><br/>
<img class="img img-responsive center-block" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg5072WN4fJcMuSMfM3uO8AsdTEmMH3vNZ75KORkEzkJsE87Hui0ZtXwvbKtPNvR097t7e08rLCavK5czrpFulLCbq4LlZOqNfYznFKTmKU15PWAvXPBgJeCbrYzI1OVQnYkL7DyXdbDtFF/s640/cli+ng+generate+component.JPG" />
<br />
It has created a folder home, with home component file, home view file, home test file and a home css file. With this it updated the app module file to include this component in the declarations array.
<br/><br/>
<img class="img img-responsive center-block" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjq2NwDlWCoBxbWofTQNuiIZLwdCwMNqGekRc-vaUxdUfIP-fqiNeFUEbFQddC6lHSIy4O0l-w2M2nNcNMXrZxo5OlLaXJUdVHLhroWfiLHEqqu_2k1lkoMy6KalDLiC5DwJnhDI6BQl01B/s480/cli+ng+generate+component+app+module.JPG" />
<br />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Post body ad responsive -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-4262325767595391" data-ad-format="auto" data-ad-slot="9970526860" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br/>
<h3>
ng lint</h3>
This command is used to do <strong>Code Analysis</strong>. A developer can leave a code smell in the source code which can lead to performance issues or bugs etc which were not intended to occur at first place. This helps us analysing with some basic code checks.
<br />
For e.g. in home.component.ts I have added this line of code - "var a = 0;". Then when I ran "ng lint", it provided me this code analysis.
<br /><br/>
<img class="img img-responsive center-block" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEis0jiO36vynqRlk6dkB-IMSIvtLeXcydGxey1GAboULD2nJsFB0jN-4DRH5_jB0kQmeEZF_7GkTq_MC_H8MS4jj9yssU9DXwExem7JeR22LaBh0HUmspsW45ziTiCLefY9e769g8cBAmEJ/s640/cli+ng+lint.JPG" />
<br />
<h3>
ng test</h3>
This command is used to unit test our spec files for each component, pipes, directives and services. Remember when we created a new component using "ng generate component", along with other files it created a spec file. That is our unit test file for the component.
The test build is executed via <strong>Karma.</strong>
<br /><br/>
<img class="img img-responsive center-block" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEib9OzP3rrtXNeTjjre6rsLkd8_yvxUpgBD1Mkib7pVnmu_UDbXWdMlFLhcApigXHv5awhOD-h-r58vKVFuZabO63LKNQFBc6mCGJSDtGlLqA5nHBYARTgAOhAHK0ofm_koLD4W7zEmf4tr/s480/cli+ng+test.JPG" />
<br />
<strong>Code coverage</strong> - If you want to run your test with code coverage, you can do with <strong>"ng test --code-coverage"</strong>
<br />
<h3>
ng e2e</h3>
This command is used to run the end to end test via <u><strong>Protractor<strong> which is end to end test framework for Angular</strong></strong></u>. Executing this command will open the browser, renders your angular app and run test cases. It is a real user like application testing.
<br />
<h3>
ng build</h3>
This command is used to compile our code in an output directory. Lets try <strong>"ng build"</strong> in our welcome app.
<br /><br/>
<img class="img img-responsive center-block" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEizY18PMMTmEbOboblhckRF9Gk5zCfuWPHMx6SMWKvywHiEXhrLzeZrU0AIwWB-ZXrgJBVqX_OW4YXpnY81UsDehpCVeYVVKV92hQlw7v3xtxvN6lkg5TBb2fcPRXVla0ZFHyIUicWV1P3d/s320/cli+ng+build.JPG" />
<br />
It also provides us with other options, for e.g. <strong>"--prod"</strong> switch minifies the code, does tree shaking, pre compiles file (Ahead-Of-Time) and generates its hashed file. Lets try this as well.
<br /><br/>
<img class="img img-responsive center-block" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg0VnDITOrX2CyuM1bYAYaBrYV4Vse1N1aAZDuP7wv49LilhWpIRBD3WJlgDzzoebCXFoSx97srRlRuvXmtWUoAQwAm0al1qA_KI0UKgaW1uPVawhldbTBYduGeNf_nNAWih9jrUc5GCAae/s640/cli+ng+build+prod.JPG" />
<br />
Look how it created a minimal set of file.
<br /><br/>
<img class="img img-responsive center-block" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiADjh3tcyDkzQ0aFeNoIxX3Un9ukwGEltJ6wZuIjXvTq2KXeYvm6TKt4eVapK73WsnwWKUA_LZRiIpDaJcvrsKsUaftXsVxhFPGQIz1_DxR4heOk5srBH8hCBn-gjaU5HqTOCs5YpuGOZO/s480/cli+ng+build+prod+code.JPG" />
<br />
The hash code is added so that in case of a new deployment, the browser will pick the latest resource file. Also, it has minified/uglified the source files necessary for prod. It also precompiled Angular (<strong>AOT</strong>) so that the app loads faster. For AOT, plese refer - <a href="https://angular.io/guide/aot-compiler" target="_blank">https://angular.io/guide/aot-compiler</a>
<br/>
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Post body ad responsive -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-4262325767595391" data-ad-format="auto" data-ad-slot="9970526860" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br/>
* Please create a blank folder and try executing these commands. In case of any issues or query, please comment below, I would be happy to assist you.
</div>
Satya Jugranhttp://www.blogger.com/profile/02579918194785863102noreply@blogger.com0tag:blogger.com,1999:blog-4672721440989923845.post-55320741666162248582017-10-01T02:09:00.000-07:002019-01-10T05:35:24.143-08:00Angular 5 : Module and Feature Modules<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<img class="img img-responsive center-block" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhlZPcihQZ5VJBu6y0HgtiL3bK-qYUrdAq3cd6Ccc5YYqAWd-fhA5vETzJCPT_TVmLA-osdY2liW5CsySFSsodl_YbfooTsAKThUG-HgnCpu4Vt_8OOC-W57ZmfMGtUTYM67F4pU9pOzfnH/s640/angular-module-and-feature-modules.JPG" /></div>
<strong><br /></strong>
<p> <strong>Important announcement</strong> : We are moving all our content to new website - <a href="https://witscad.com/courses"> Witscad Courses </a>. You can find the updated complete Angular course here - <a href="https://witscad.com/course/complete-angular-tutorial">A Complete Angular Tutorial</a>. Feel free to visit. </p>
<strong>Angular modules</strong> are designed to distribute our application into blocks of different modules which are more manageable. As our application starts growing incorporating more features and functionalities, it becomes tedious to manages if we keep on adding code into our single block of application. Then there comes a time when we have to code our new big features into a different module. We then use that module in our main application module.
<br />
<br />
<strong>Angular modules</strong> are independent block of distributable code. These can be exported as a library. For e.g. Angular provides us with <strong>BrowserModule, HttpModule, FormsModule</strong> etc. Similarly we can make our own Angular module which can be used in one or more application depending on the scope of functionality which we are building,
<br />
<br />
It is much easier to do with Angular Modules.
<br />
<br />
An <strong>Angular Module</strong> is a class with <strong>ngModule</strong> decorator.
<br />
<h2>
Features of and Angular module</h2>
It declares its own set of Components, Directives and Pipes.<br />
It can be exported as an angular module where other modules con consume its components, directives and pipes.<br />
It provide services to itself and other modules.<br />
It can import other modules in its own module declaration and use their components, directives and pipes.<br />
<br />
If we look at our default app.module.ts file, we will find something similar code like this:
<br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #0000aa;">import</span> {Component, NgModule} from <span style="color: #aa5500;">'@angular/core'</span>
<span style="color: #0000aa;">import</span> {BrowserModule} from <span style="color: #aa5500;">'@angular/platform-browser'</span>
<span style="color: #0000aa;">export</span> <span style="color: #0000aa;">class</span> App {
<span style="color: #0000aa;">constructor</span>() {
}
}
NgModule({
imports: [ BrowserModule ],
declarations: [ App],
providers : [],
bootstrap: [ App ]
})
<span style="color: #0000aa;">export</span> <span style="color: #0000aa;">class</span> AppModule {}
</pre>
</div>
The <strong>@ngModule()</strong> directive have some different sets of settings. Let's look at them one by one.
<br />
<h4>
imports</h4>
This is an array where we define other modules that we want to import in our main application module such as <strong>BrowserModule, FormsModule</strong> or any other third party module. One thing to note that when we export our module, all other modules that we imported are also available in our exported module.
If A import B and C imports A, this means C does not have access to B.
<br />
<h4>
declaration</h4>
This is an array which defines all the components, directives, pipes that belong to our angular module. Each of them must belong to only one angular module.
<br />
<h4>
bootstrap</h4>
This is used to load the application module in Angular ecosystem. The application must bootstrap at least one component which is the root application component. It should only be used in the root application module.
<br />
<h4>
exports</h4>
This is an array that is used to export components, directives and pipes to other module.
<br />
<h4>
providers</h4>
This is an array where we define services of our module. This can be either at root level or any component level. If we have defined our service in providers array at root level, then that service will also be available to all child components. If we want a service available to a particular component only then we define that service to that component's provider array only.
<br />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Post body ad responsive -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-4262325767595391" data-ad-format="auto" data-ad-slot="9970526860" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<h2>
Feature Module</h2>
A <strong>Feature Module</strong> in Angular is a module other than our main application root module <u>that is decorated by <strong>@ngModule()</strong> decorator</u> and hence share the same property configurations like application root module. You can also say it a custom module or an external module, but <strong>Feature Module</strong> is an Angular way of saying wherein we separate our features of our main application into a different module.
<br />
<br />
As our application starts growing bigger, it's better to re-factor at early stage so that the application stays manageable. <u>Implementing Feature modules is a way of re-factoring our application.</u>
<br />
<br />
<h3>
Example application - Mail Client</h3>
Ok, so now we will move on to building an example application which is <strong>Mail Client</strong>. We will introduce two Feature modules - <strong>Mail Box</strong> and <strong>Address Book</strong> in our main application root module i.e. Mail Client.
<br />
<h4>
MailClient component</h4>
Here we are just showing the version of the mail client which we input from main application component.
<br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #0000aa;">import</span> {Component, Input} from <span style="color: #aa5500;">'@angular/core'</span>
@Component({
selector: <span style="color: #aa5500;">'mail-client'</span>,
template: `
<span style="color: dodgerblue; font-weight: bold;"><div></span>
<span style="color: dodgerblue; font-weight: bold;"><h2></span>MailClient : v - {{version}} <span style="color: dodgerblue; font-weight: bold;"></h2></span>
<span style="color: dodgerblue; font-weight: bold;"></div></span>
`
})
<span style="color: #0000aa;">export</span> <span style="color: #0000aa;">class</span> MailClient {
@Input() version:<span style="color: #00aaaa;">number</span>;
<span style="color: #0000aa;">constructor</span>(){
}
}
</pre>
</div>
<h4>
MailBox Feature module</h4>
This is our <strong>MailBox Feature Module</strong> which have a <strong>MailBox component</strong> and a <strong>MailBox service</strong>
<br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #0000aa;">import</span> { NgModule } from <span style="color: #aa5500;">'@angular/core'</span>;
<span style="color: #0000aa;">import</span> { CommonModule } from <span style="color: #aa5500;">'@angular/common'</span>;
<span style="color: #0000aa;">import</span> { MailBoxComponent } from <span style="color: #aa5500;">'./mailBox.component'</span>
<span style="color: #0000aa;">import</span> { MailBoxService } from <span style="color: #aa5500;">'./mailBox.service'</span>
@NgModule({
imports: [ CommonModule ],
declarations: [ MailBoxComponent ],
exports: [ MailBoxComponent ],
providers: [ MailBoxService ]
})
<span style="color: #0000aa;">export</span> <span style="color: #0000aa;">class</span> MailBoxModule { }
</pre>
</div>
<h4>
MailBox Service</h4>
It contains one method which provides inbox mails (values hard-codes for demo, can be extended).
<br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #0000aa;">import</span> {Injectable} from <span style="color: #aa5500;">'@angular/core'</span>
@Injectable()
<span style="color: #0000aa;">export</span> <span style="color: #0000aa;">class</span> MailBoxService {
<span style="color: #0000aa;">constructor</span>(){
}
getInboxMails():<span style="color: #00aaaa;">string</span>[] {
<span style="color: #0000aa;">return</span> [
<span style="color: #aa5500;">"Welcome to MailClient"</span>,
<span style="color: #aa5500;">"Daily Newsletter"</span>,
<span style="color: #aa5500;">"20% discount on this product"</span>
];
}
}
</pre>
</div>
<h4>
MailBox component</h4>
It displays all the mails provided by the MailBox Service.
<br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #0000aa;">import</span> { Component } from <span style="color: #aa5500;">'@angular/core'</span>
<span style="color: #0000aa;">import</span> { MailBoxService } from <span style="color: #aa5500;">'./mailBox.service'</span>
@Component({
selector: <span style="color: #aa5500;">'mail-box'</span>,
template: `
<span style="color: dodgerblue; font-weight: bold;"><div></span>
<span style="color: dodgerblue; font-weight: bold;"><h2></span>Mail Box<span style="color: dodgerblue; font-weight: bold;"></h2></span>
<span style="color: dodgerblue; font-weight: bold;"><div</span> <span style="color: dodgerblue;">ngFor=</span><span style="color: #aa5500;">'let ibMail of inboxMails; let idx = index'</span><span style="color: dodgerblue; font-weight: bold;">></span>
<span style="color: dodgerblue; font-weight: bold;"><div></span>{{idx+1}} - {{ibMail}}<span style="color: dodgerblue; font-weight: bold;"></div></span>
<span style="color: dodgerblue; font-weight: bold;"></div></span>
<span style="color: dodgerblue; font-weight: bold;"></div></span>
`
})
<span style="color: #0000aa;">export</span> <span style="color: #0000aa;">class</span> MailBoxComponent <span style="color: #0000aa;">implements</span> OnInit{
inboxMails:<span style="color: #00aaaa;">string</span>[];
<span style="color: #0000aa;">constructor</span>(<span style="color: #0000aa;">private</span> _service: <span style="color: #00aaaa;">MailBoxService</span>){
}
ngOnInit(){
<span style="color: #0000aa;">this</span>.inboxMails = <span style="color: #0000aa;">this</span>._service.getInboxMails();
}
}
</pre>
</div>
<br />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Post body ad responsive -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-4262325767595391" data-ad-format="auto" data-ad-slot="9970526860" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<h4>
AddressBook Module</h4>
In the similar way, we will create another Feature module - <strong>Address Book Feature Module</strong>. This will have the <strong>AddressBook component</strong> and an <strong>AddressBook service</strong>.
<br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #0000aa;">import</span> { NgModule } from <span style="color: #aa5500;">'@angular/core'</span>;
<span style="color: #0000aa;">import</span> { CommonModule } from <span style="color: #aa5500;">'@angular/common'</span>;
<span style="color: #0000aa;">import</span> { AddressBookComponent } from <span style="color: #aa5500;">'./addressBook.component'</span>
<span style="color: #0000aa;">import</span> { AddressBookService } from <span style="color: #aa5500;">'./addressBook.service'</span>
@NgModule({
imports: [ CommonModule ],
declarations: [ AddressBookComponent ],
exports: [ AddressBookComponent ],
providers: [ AddressBookService ]
})
<span style="color: #0000aa;">export</span> <span style="color: #0000aa;">class</span> AddressBookModule { }
</pre>
</div>
<h4>
AddressBookService</h4>
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #0000aa;">import</span> {Injectable} from <span style="color: #aa5500;">'@angular/core'</span>
@Injectable()
<span style="color: #0000aa;">export</span> <span style="color: #0000aa;">class</span> AddressBookService {
<span style="color: #0000aa;">constructor</span>(){
}
getContacts():<span style="color: #00aaaa;">string</span>[] {
<span style="color: #0000aa;">return</span> [
<span style="color: #aa5500;">"Alice (alice@example.com)"</span>,
<span style="color: #aa5500;">"Bob (bob@example.com)"</span>,
<span style="color: #aa5500;">"Chris (chris@example.com)"</span>
];
}
}
</pre>
</div>
<h4>
AddressBookComponent</h4>
<!-- HTML generated using hilite.me --><br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #0000aa;">import</span> { Component } from <span style="color: #aa5500;">'@angular/core'</span>
<span style="color: #0000aa;">import</span> { AddressBookService } from <span style="color: #aa5500;">'./addressBook.service'</span>
@Component({
selector: <span style="color: #aa5500;">'address-book'</span>,
template: `
<span style="color: dodgerblue; font-weight: bold;"><div></span>
<span style="color: dodgerblue; font-weight: bold;"><h2></span>Address Book<span style="color: dodgerblue; font-weight: bold;"></h2></span>
<span style="color: dodgerblue; font-weight: bold;"><div</span> <span style="color: dodgerblue;">ngFor=</span><span style="color: #aa5500;">'let contact of contacts; let idx = index'</span><span style="color: dodgerblue; font-weight: bold;">></span>
<span style="color: dodgerblue; font-weight: bold;"><div></span>{{idx+1}} - {{contact}}<span style="color: dodgerblue; font-weight: bold;"></div></span>
<span style="color: dodgerblue; font-weight: bold;"></div></span>
<span style="color: dodgerblue; font-weight: bold;"></div></span>
`
})
<span style="color: #0000aa;">export</span> <span style="color: #0000aa;">class</span> AddressBookComponent <span style="color: #0000aa;">implements</span> OnInit{
contacts : <span style="color: #00aaaa;">string</span>[];
<span style="color: #0000aa;">constructor</span>(<span style="color: #0000aa;">private</span> _service : <span style="color: #00aaaa;">AddressBookService</span>){
}
ngOnInit(){
<span style="color: #0000aa;">this</span>.contacts = <span style="color: #0000aa;">this</span>._service.getContacts();
}
}
</pre>
</div>
<strong>Note</strong> : Both in the <strong>MailBoxModule</strong> and <strong>AddressBookModule</strong>, we are <u>not importing BrowserModule</u> but we are <u>importing CommonModule</u>. The reason is that some essential services to launch and run a browser app is provided by BrowserModule. BrowserModule also re-exports CommonModule from @angular/common. We should not import BrowserModule in any other module. Feature modules and lazy-loaded modules should import CommonModule instead.
<br />
<h4>
Full source code is here</h4>
<a href="https://embed.plnkr.co/jfhvoV/" target="_blank">https://embed.plnkr.co/jfhvoV/</a></div>
Satya Jugranhttp://www.blogger.com/profile/02579918194785863102noreply@blogger.com2tag:blogger.com,1999:blog-4672721440989923845.post-53754890972674245192017-09-29T12:17:00.000-07:002019-01-10T05:35:37.909-08:00Angular 5 : Routing and Navigation<div dir="ltr" style="text-align: left;" trbidi="on">
<img class="img img-responsive center-block" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjlZO7qGBPjuHQhCDGsrRivTqyyoIOtEhyphenhyphenb_cqxk60D5jxsVFghh92P_HKT-emWj7YzOhpDpCiALcCpyHPxnvGLp73BGVDXyZ7dmBzXR-LTclAo9G3LSvZBqFZvw0Qil8QIyynAi6MB2MEv/s640/angular-routing-and-navigation.JPG" />
<strong>Routing</strong> is a functionality that enable us to move from one view to another. Angular <strong>Router</strong> does this for us. In a Web Application, we generally do navigation by entering URL, click of hyper-links and buttons, dynamic navigation through JavaScript etc.
<br />
<p> <strong>Important announcement</strong> : We are moving all our content to new website - <a href="https://witscad.com/courses"> Witscad Courses </a>. You can find the updated complete Angular course here - <a href="https://witscad.com/course/complete-angular-tutorial">A Complete Angular Tutorial</a>. Feel free to visit. </p>
The Angular Router wraps all these instructions and provide us with seamless functionalities that, as a developer, we can implements in most easy and robust way to provide routing features in our Angular application.
<br />
<h3>
How Angular Router works</h3>
1. Every view is associated with a component. The first step is to configure routes for our view components.<br />
2. We define some router options on the component.<br />
3. We define router actions on the component.<br />
4. We activate the route when user does the navigation or any routing action.<br />
5. When a route gets activated for a component, it displays the view of that component.<br />
<h3>
Importing and Configuring Routes</h3>
In your 'app.modules.ts', import <strong>RouterModule</strong> from <strong>'@angular/router'</strong>.
<br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #0000aa;">import</span> {RouterModule} from <span style="color: #aa5500;">'@angular/router'</span>
@NgModule({
imports: [ BrowserModule, RouterModule.forRoot([]) ],
declarations: [ App ],
bootstrap: [ App ]
})
<span style="color: #0000aa;">export</span> <span style="color: #0000aa;">class</span> AppModule {}
</pre>
</div>
<br />
This will register the Angular router provider. The <strong>forRoot([])</strong> method signifies that the routes are available to your root application module.
<br />
By default HTML5 URLs are configured for routing, if you want to use Hash(#) style routing like Angular 1 provided, then add an option to the forRoot() method.
<br />
<pre>RouterModule.forRoot([], {useHash : true})</pre>
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Post body ad responsive -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-4262325767595391" data-ad-format="auto" data-ad-slot="9970526860" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br />
<h2>
Example Application</h2>
Let's make our example application which will make use of Angular Router and will show how the routes are configured, activated and used. We are making a sample grocery app which will show different category of food products and user can click on each category to navigate to its view.
<br />
<h3>
Creating food category component classes</h3>
Let's create three food category components - <strong>Fruits</strong>, <strong>Vegetables</strong> and <strong>Snacks</strong>.
<br />
This is our Fruits component class:
<br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #0000aa;">import</span> {Component} from <span style="color: #aa5500;">'@angular/core'</span>
@Component({
template: `
<span style="color: dodgerblue; font-weight: bold;"><h2></span>Fruits<span style="color: dodgerblue; font-weight: bold;"></h2></span>
<span style="color: dodgerblue; font-weight: bold;"><p></span>Choose fruits<span style="color: dodgerblue; font-weight: bold;"></p></span>
<span style="color: dodgerblue; font-weight: bold;"><select></span>
<span style="color: dodgerblue; font-weight: bold;"><option></span>Apple<span style="color: dodgerblue; font-weight: bold;"></option></span>
<span style="color: dodgerblue; font-weight: bold;"><option></span>Banana<span style="color: dodgerblue; font-weight: bold;"></option></span>
<span style="color: dodgerblue; font-weight: bold;"><option></span>Oranges<span style="color: dodgerblue; font-weight: bold;"></option></span>
<span style="color: dodgerblue; font-weight: bold;"><option></span>Grapes<span style="color: dodgerblue; font-weight: bold;"></option></span>
<span style="color: dodgerblue; font-weight: bold;"><option></span>Pomgranates<span style="color: dodgerblue; font-weight: bold;"></option></span>
<span style="color: dodgerblue; font-weight: bold;"></select></span>
`
})
<span style="color: #0000aa;">export</span> <span style="color: #0000aa;">class</span> Fruits {}
</pre>
</div>
The other two component classes - <strong>Vegetable</strong> and <strong>Snacks</strong> are similar at this moment. We will later modify our Snacks component to illustrate more routing examples.
<br />
<h2>
Configuring Routes</h2>
In our main application component, we will add a navigation bar and add routing links to Fruits, Vegetables and Snacks components:
<br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #0000aa;">import</span> {RouterModule} from <span style="color: #aa5500;">'@angular/router'</span>
<span style="color: #0000aa;">import</span> {Fruits} from <span style="color: #aa5500;">'./fruits'</span>
<span style="color: #0000aa;">import</span> {Vegetables} from <span style="color: #aa5500;">'./vegetables'</span>
<span style="color: #0000aa;">import</span> {Snacks} from <span style="color: #aa5500;">'./snacks'</span>
Component({
selector: <span style="color: #aa5500;">'my-app'</span>,
template: `
<span style="color: dodgerblue; font-weight: bold;"><div><h1></span>Select Food Category<span style="color: dodgerblue; font-weight: bold;"></h1></div></span>
<span style="color: dodgerblue; font-weight: bold;"><nav><h3></span>
<span style="color: dodgerblue; font-weight: bold;"><a</span> <span style="color: dodgerblue;">[routerLink]="['/fruits']" routerLinkActive=</span><span style="color: #aa5500;">"active"</span><span style="color: dodgerblue; font-weight: bold;">></span>Fruits<span style="color: dodgerblue; font-weight: bold;"></a></span>
<span style="color: dodgerblue; font-weight: bold;"><a</span> <span style="color: dodgerblue;">[routerLink]="['/vegetables']" routerLinkActive=</span><span style="color: #aa5500;">"active"</span><span style="color: dodgerblue; font-weight: bold;">></span>Vegetables<span style="color: dodgerblue; font-weight: bold;"></a></span>
<span style="color: dodgerblue; font-weight: bold;"><a</span> <span style="color: dodgerblue;">[routerLink]="['/snacks', '1']" routerLinkActive=</span><span style="color: #aa5500;">"active"</span><span style="color: dodgerblue; font-weight: bold;">></span>Normal Snacks<span style="color: dodgerblue; font-weight: bold;"></a></span>
<span style="color: dodgerblue; font-weight: bold;"><a</span> <span style="color: dodgerblue;">[routerLink]="['/snacks', '2']" routerLinkActive=</span><span style="color: #aa5500;">"active"</span><span style="color: dodgerblue; font-weight: bold;">></span>Fat Free Snacks<span style="color: dodgerblue; font-weight: bold;"></a></span>
<span style="color: dodgerblue; font-weight: bold;"></h3></nav></span>
<span style="color: dodgerblue; font-weight: bold;"><router-outlet></router-outlet></span>
`,
})
<span style="color: #0000aa;">export</span> <span style="color: #0000aa;">class</span> App {
<span style="color: #0000aa;">constructor</span>() {
}
}
<span style="color: #0000aa;">const</span> appRoutes: <span style="color: #00aaaa;">Routes</span> = [
{ path: <span style="color: #aa5500;">'fruits'</span>, component: <span style="color: #00aaaa;">Fruits</span> },
{ path: <span style="color: #aa5500;">'vegetables'</span>, component: <span style="color: #00aaaa;">Vegetables</span> },
{ path: <span style="color: #aa5500;">'snacks/:id'</span>, component: <span style="color: #00aaaa;">Snacks</span> },
{ path: <span style="color: #aa5500;">''</span>, redirectTo: <span style="color: #aa5500;">'/'</span>, pathMatch: <span style="color: #aa5500;">'full'</span> },
{ path: <span style="color: #aa5500;">'**'</span>, component: <span style="color: #00aaaa;">PageNotFound</span> }
];
</pre>
</div>
<h4>
Ok, so let's deep dive into the above code</h4>
First, see this line of code <br />
<pre><span style="color: dodgerblue; font-weight: bold;"><a</span> <span style="color: dodgerblue;">[routerLink]="['/fruits']" routerLinkActive=</span><span style="color: #aa5500;">"active"</span><span style="color: dodgerblue; font-weight: bold;">></span>Fruits<span style="color: dodgerblue; font-weight: bold;"></a></span></pre>
Here, we are telling angular that to link a route <strong>'./fruits'</strong> in its current route. The <strong>routeLinkActivate</strong> tells Angular that we need to activate this route. We can not navigate to a route without activating it. This is to make Angular routing more flexible.
<br />
We can also pass parameters to a particular route.
<br />
<pre><span style="color: dodgerblue; font-weight: bold;"><a</span> <span style="color: dodgerblue;">[routerLink]="['/snacks', '1']" routerLinkActive=</span><span style="color: #aa5500;">"active"</span><span style="color: dodgerblue; font-weight: bold;">></span>Normal Snacks<span style="color: dodgerblue; font-weight: bold;"></a></span></pre>
If you see, we are passing second item to the array of <strong>routerLink</strong>. This item will be passed in the URL like <strong>/snacks/1</strong> and will be provided to the target component class which is configured for this route. We will see later how we consume this parameter in the router component class.
<br />
Suppose, we have entered just the site's address without any route. Then we sometimes need to redirect to some other route, may be a login page or some other welcome page. This is how it is done.
<br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;">{ path: <span style="color: #aa5500;">''</span>, redirectTo: <span style="color: #aa5500;">'/'</span>, pathMatch: <span style="color: #aa5500;">'full'</span> }
</pre>
</div>
<strong>pathMatch full</strong> - It indicates the Router to match the path only when the path is '/' is there and not './<something>'
<br />
If nothing matches, the a default path matches which is **
<br />
</something><br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;">{ path: <span style="color: #aa5500;">'**'</span>, component: <span style="color: #00aaaa;">PageNotFound</span> }
</pre>
</div>
The <strong><router-outlet></strong> directive let's the component's view display here. Path match properties matches the path in a sequence, so any path that matches first will be considered for routing.
<br />
You need to add <strong><base href="/"></strong> after head opening tag in <strong>index.html</strong> to let Angular know as how to construct the paths. All files, js, html, css will then reference with this path.
<br />
This is useful when we have multiple applications hosted in our server. In this case we can give application name here. For eg. <em><base href="/PhotoViewer"></em>
Then the URL will be <em>http://www.example.com/PhotoViewer/</em>. All other router paths will be composed to this path.
<br />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Post body ad responsive -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-4262325767595391" data-ad-format="auto" data-ad-slot="9970526860" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<h2>
Route Parameters</h2>
Till now we have configured routes. As mentioned above, we need to consume our Snacks component route parameter. This is how we do it.
<br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #0000aa;">import</span> {ActivatedRoute} from <span style="color: #aa5500;">'@angular/router'</span>
<span style="color: #0000aa;">import</span> {Observable} from <span style="color: #aa5500;">'rxjs/Observable'</span>
<span style="color: #0000aa;">import</span> <span style="color: #aa5500;">'rxjs/add/operator/switchMap'</span>;
<span style="color: #0000aa;">import</span> <span style="color: #aa5500;">'rxjs/add/observable/of'</span>;
<span style="color: #0000aa;">export</span> <span style="color: #0000aa;">class</span> Snacks <span style="color: #0000aa;">implements</span> OnInit{
snackType:<span style="color: #00aaaa;">number</span>;
<span style="color: #0000aa;">constructor</span>(<span style="color: #0000aa;">private</span> _route : <span style="color: #00aaaa;">ActivatedRoute</span>){
}
ngOnInit(){
<span style="color: #0000aa;">this</span>._route.paramMap
.switchMap((params: <span style="color: #00aaaa;">ParamMap</span>) => {
<span style="color: #0000aa;">return</span> Observable.of(params.get(<span style="color: #aa5500;">'id'</span>));
})
.subscribe(id => {<span style="color: #0000aa;">this</span>.snackType = +id;});
}
</pre>
</div>
We first import the <strong>ActivatedRoute</strong> from <strong>'@angular/route'</strong> and inject it into our constructor. <strong>ActivatedRoute</strong> provide us with the current route information (path, URL, parameters etc). The <strong>ActivatedRoute</strong> <em>paramaMap</em> property has one method get which helps to get the named parameter from the URL. One thing to note that we are observing the <em>params.get('id')</em> value. This is required when we want to navigate to same route but with different route parameter.
<br /><br />
<strong>For e.g</strong> if we are navigating from <em>/snacks/1</em> to <em>/snacks/2</em>, since the component is same so <strong>ngOnInit</strong> is not going to be called again. So we starts observing on the parameter itself as soon as the component gets rendered.
<br /><br />
In the subscribe function, we are just assigning our snackType property to the route parameter. In our template view, we utilize this property as:
<br />
<pre>Snacks | {{snackType == 1? 'Normal' : 'Fat free'}}</pre>
<strong>Note :</strong> RxJS is a separate topic that is something not going to be covered here. Please refer - <a href="http://reactivex.io/rxjs" target="_blank">http://reactivex.io/rxjs</a> for detailed documentation.
<br />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Post body ad responsive -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-4262325767595391" data-ad-format="auto" data-ad-slot="9970526860" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<h2>
Protecting the Routes - Route Guards</h2>
There are several time when we want user to restrict to some routes. It can be one of the following scenarios:
<br />
<ul>
<li>User should not access the app before login, so we need to deny access to main application routes.</li>
<li>Some users may be administrators, some normal users or some may be guest users depending on the application's user access layer. So we need to restrict access to certain routes accordingly.</li>
<li>If some http response is in progress, you might not want the user to navigate to some other route. It can be the case where user save a form and it is still in progress.</li>
<li>You might want to pre-fetch some data before actually displaying the component, may be to check some validation. In this case too, you need to protect that route.</li>
</ul>
<br />
The router supports multiple guard interfaces:
<br />
<strong>CanActivate</strong> - intercept navigation to a route.<br />
<strong>CanDeactivate</strong> - intercept navigation away from the current route.<br />
<strong>Resolve</strong> - pre-fetch data before route activation.<br />
<strong>CanLoad</strong> - intercept asynchronous routing<br />
<br />
Continuing with our example, we will now make a service <strong>RouteGuardService</strong>
<br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #0000aa;">import</span> {Injectable} from <span style="color: #aa5500;">'@angular/core'</span>
<span style="color: #0000aa;">import</span> {CanActivate, ActivatedRouteSnapshot} from <span style="color: #aa5500;">'@angular/router'</span>
@Injectable()
<span style="color: #0000aa;">export</span> <span style="color: #0000aa;">class</span> RouteGuardService <span style="color: #0000aa;">implements</span> CanActivate {
canActivate(route: <span style="color: #00aaaa;">ActivatedRouteSnapshot</span>): <span style="color: #0000aa;">boolean</span> {
<span style="color: #0000aa;">let</span> snackTypeId = route.url[<span style="color: #009999;">1</span>].path;
<span style="color: #0000aa;">if</span>(snackTypeId == <span style="color: #009999;">2</span>){
alert(<span style="color: #aa5500;">'Not available for guest users!'</span>);
<span style="color: #0000aa;">return</span> <span style="color: #0000aa;">false</span>;
}
<span style="color: #0000aa;">return</span> <span style="color: #0000aa;">true</span>;
}
}
</pre>
</div>
We are importing <strong>CanActivate</strong> and <strong>ActivatedRouteSnapshot</strong>. We implement the <strong>CanActivate</strong> interface which has one method to implement <strong><em>canActivate()</em></strong> (remember it intercepts navigation to route). With this, we inject <strong>ActivatedRouteSnapshot</strong> to get the current activated route information.
Here ,we are just checking the snacks route parameter and if it is 2, we are showing an alert. Now, we need to do some changes in our main application module. First import the <strong>RouteGuardService</strong>
<br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #0000aa;">import</span> {RouteGuardService} from <span style="color: #aa5500;">'./routeguardservice'</span>
</pre>
</div>
Then Replace <br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;">{ path: <span style="color: #aa5500;">'snacks/:id'</span>, component: <span style="color: #00aaaa;">Snacks</span> }
</pre>
</div>
With <br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;">{ path: <span style="color: #aa5500;">'snacks/:id'</span>, canActivate : [RouteGuardService], component: <span style="color: #00aaaa;">Snacks</span> }
</pre>
</div>
See that we are passing one more option <strong>canActivate</strong> and assigning it to an array. This array contains the CanActivate implemented Service, which will be invoked every time the Angular Router hits this path.
<br />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Post body ad responsive -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-4262325767595391" data-ad-format="auto" data-ad-slot="9970526860" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<h2>
Summary</h2>
So we have learnt several things about Angular routing and navigation:<br />
1. What is Angular Routing and how it works.<br />
2. Configuring routes.<br />
3. Using route parameters.<br />
4. Protecting routes with Route Guards.<br />
<br />
For in-depth documentation please refer Angular official documentation - https://angular.io
<br /><br />
Full working source code of this example is available here - <a href="https://embed.plnkr.co/y647y2fwluWas8YrFXxK/" target="_blank">https://embed.plnkr.co/y647y2fwluWas8YrFXxK/</a>
</div>
Satya Jugranhttp://www.blogger.com/profile/02579918194785863102noreply@blogger.com2tag:blogger.com,1999:blog-4672721440989923845.post-45041483591272156642017-09-28T12:00:00.001-07:002019-01-10T05:35:50.684-08:00Angular 5 : Consuming RESTful Service with HttpClient and RxJS<div dir="ltr" style="text-align: left;" trbidi="on">
<img class="img img-responsive center-block" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEipVnIV86YZWC80_biwLyxkY8Ph1vLaJJTXdDcTnUDnZcDWY9uahl446lENnsa2St1uQlkre-scKLb_eos_LhTv0MpH-ICGBtlT_F9fFcKHDJcGkJiTCSkhfqHOE2kk1zfeii5JACdRGVB7/s640/angular-consuming-restful-service.JPG" /><br />
<p> <strong>Important announcement</strong> : We are moving all our content to new website - <a href="https://witscad.com/courses"> Witscad Courses </a>. You can find the updated complete Angular course here - <a href="https://witscad.com/course/complete-angular-tutorial">A Complete Angular Tutorial</a>. Feel free to visit. </p>
<strong>REST</strong> or <strong>HTTP</strong> based services are the primary requirements of single page applications to retrieve the data and gel into the web application. Angular offers its inbuilt http client service which wraps the major functions for requesting the data from server where REST service is hosted.
<br /><br/>
Angular provides <strong>HttpClient</strong> for this purpose which is packaged under <strong>@angular/common/http</strong>. Before we can use <strong>HttpClient</strong>, we have to import <strong>HttpClientModule</strong> in our main application module.
<br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #0000aa;">import</span> {NgModule} from <span style="color: #aa5500;">'@angular/core'</span>;
<span style="color: #0000aa;">import</span> {BrowserModule} from <span style="color: #aa5500;">'@angular/platform-browser'</span>;
<span style="color: #0000aa;">import</span> {HttpClientModule} from <span style="color: #aa5500;">'@angular/common/http'</span>;
@NgModule({
imports: [
BrowserModule,
HttpClientModule,
],
})
<span style="color: #0000aa;">export</span> <span style="color: #0000aa;">class</span> MyAppModule {}
</pre>
</div>
<strong>HttpClient</strong> is best consumed when used with <strong>Observables</strong>. You must be asking a question - What is an Observable here?
An <strong>Observable</strong> is simply a collection of future events which arrives asynchronously over time.<br />
<img class="img img-responsive center-block" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhT4zdkvNg5B3bxQZBfaFF0GBpl7v09j0h-vzLhZJOQZikKrf6fRr2ayWLLp2223uhxJ_Y9ILdFuf2cO0YTuTKsDuXHhpCF_ZiaRvDLF3ZEyyXOlZqQoQfiZ1mggmx23CtvolxVCzBIoImc/s640/RxMarble.JPG" />
<h3>RxJS</h3>
An Observable is a class provided by RxJs. To learn more about RxJS, please visit <a href="http://reactivex.io/rxjs/" target="_blank">http://reactivex.io/rxjs/</a>
<br />
<strong>Observables</strong> are pretty much similar to promise or callbacks but the main advantage is they are lazy loaded. Observables will not be called till the time any subscriber invoked on it.
<br />
Feel free to play around at RxMarbles website <a href="http://rxmarbles.com" target="_blank">http://rxmarbles.com</a> to get to know how values are observed over time.
<br />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Post body ad responsive -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-4262325767595391" data-ad-format="auto" data-ad-slot="9970526860" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br/>
<h2>Building our example app</h2>
Let us start with an example. Here we are building a simple survey which will ask a question and user can choose from one of the four option. We will get our survey data from our Http service as JSON.
<br/>
Full working example is here - <a href="https://embed.plnkr.co/eKil3iBwhppDNtzqf2YH/" target="_blank">https://embed.plnkr.co/eKil3iBwhppDNtzqf2YH/</a>
<br />
<h3>Create a survey interface</h3>
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #0000aa;">export</span> <span style="color: #0000aa;">interface</span> ISurvey{
question:<span style="color: #00aaaa;">string</span>;
choices: <span style="color: #00aaaa;">string</span>[];
}
</pre>
</div>
<h3>Our Survey Data</h3>
Let's add couple of questions in our json survey data which we will request from our http service. You can add more later.
<br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;">[
{
<span style="color: dodgerblue; font-weight: bold;">"question"</span>: <span style="color: #aa5500;">"What is your favourite programming language?"</span>,
<span style="color: dodgerblue; font-weight: bold;">"choices"</span>: [<span style="color: #aa5500;">"Swift"</span>,<span style="color: #aa5500;">"Python"</span>,<span style="color: #aa5500;">"Objective-C"</span>,<span style="color: #aa5500;">"Ruby"</span>]
},
{
<span style="color: dodgerblue; font-weight: bold;">"question"</span>: <span style="color: #aa5500;">"What is your major learning source?"</span>,
<span style="color: dodgerblue; font-weight: bold;">"choices"</span>: [<span style="color: #aa5500;">"Books"</span>,<span style="color: #aa5500;">"Online Tutorials"</span>,<span style="color: #aa5500;">"Online Bootcamp courses"</span>]
}
]
</pre>
</div>
<h3>Our Survey Service</h3>
We will now add our survey service class which will provide data interaction operations to our survey class. Now, to make survey service injectable we'll import Injectable from '@angular/core' and decorate our component with @Injectable().
<br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;">@Injectable()
<span style="color: #0000aa;">export</span> <span style="color: #0000aa;">class</span> SurveyService {
..
}
</pre>
</div>
<h3>Injecting HttpClient into Survey service</h3>
Add http functionality by importing HttpClient from <strong>'@angular/common/http'</strong> and inject the HttpClient in our constructor:
<br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #0000aa;">import</span> {HttpClient, HttpErrorResponse } from <span style="color: #aa5500;">'@angular/common/http'</span>
<span style="color: #0000aa;">export</span> <span style="color: #0000aa;">class</span> SurveyService {
<span style="color: #0000aa;">constructor</span>(<span style="color: #0000aa;">private</span> _http:<span style="color: #00aaaa;">HttpClient</span>){
..
}
</pre>
</div>
<h3>Adding Observable method in Survey service</h3>
As discussed previously, we will add Rxjs Observables to work with Http services since we have values that will be received in some point of time. Observables works best in these scenarios.
<br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #0000aa;">import</span> {Observable} from <span style="color: #aa5500;">'rxjs/Observable'</span>
</pre>
</div>
Add the following, these are required for Observables operations:
<br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #0000aa;">import</span> <span style="color: #aa5500;">'rxjs/add/operator/catch'</span>;
<span style="color: #0000aa;">import</span> <span style="color: #aa5500;">'rxjs/add/operator/do'</span>;
<span style="color: #0000aa;">import</span> <span style="color: #aa5500;">'rxjs/add/operator/map'</span>;
</pre>
</div>
Now add an Observabbe method which will get the survey data using HttpClient:
<br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;">getSurveyQuestion(): Observable<ISurvey[]>{
<span style="color: #0000aa;">return</span> <span style="color: #0000aa;">this</span>._http
.get<ISurvey[]>(<span style="color: #aa5500;">'./src/survey.json'</span>)
.<span style="color: #0000aa;">do</span>(data =>console.log(<span style="color: #aa5500;">'All : '</span> + JSON.stringify(data)))
.<span style="color: #0000aa;">catch</span>(<span style="color: #0000aa;">this</span>.handleError);
}
</pre>
</div>
Look that we are returning an Observable of ISurvey[] array. <strong>Observable are lazy</strong>, an Observable method will only be invoked when a subscription is called that.
<br />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Post body ad responsive -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-4262325767595391" data-ad-format="auto" data-ad-slot="9970526860" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br/>
<h3>
Injecting our Survey Service:</h3>
Now, as we have our service ready, we will inject it in our Survey class constructor:
<br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #0000aa;">import</span> {ISurvey} from <span style="color: #aa5500;">'./isurvey'</span>
<span style="color: #0000aa;">import</span> {SurveyService} from <span style="color: #aa5500;">'./survey.service'</span>;
<span style="color: #0000aa;">export</span> <span style="color: #0000aa;">class</span> Survey {
MySurvey : <span style="color: #00aaaa;">ISurvey</span>[] = [];
<span style="color: #0000aa;">constructor</span>(<span style="color: #0000aa;">private</span> _surveyService: <span style="color: #00aaaa;">SurveyService</span>){
...
}
}
</pre>
</div>
<h3>Calling our observable method from SurveyService</h3>
<strong>We can not call that in our constructor. Why?</strong><br/>
Just for the simple reason that we can not delay the construction of our component till the time we get our json data from the network.
<br/><br/>
<strong>So, where we will call this method?</strong><br/>
Angular provides us with <strong>Lifecycle</strong> hooks. Read more here.. <a href="https://angularbytes.witspry.com/2017/09/angular-5-life-cycle-hooks.html" target="_blank">https://angularbytes.witspry.com/2017/09/angular-5-life-cycle-hooks.html</a>
<br /><br/>
One of the lifecycle hook is <strong>ngOnInit()</strong>. After our component is constructed, <strong>ngOnInit()</strong> lifecycle hook is called. So, we will implement it and call our RESTful method within this lifecycle hook.
<br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #0000aa;">export</span> <span style="color: #0000aa;">class</span> Survey <span style="color: #0000aa;">implements</span> OnInit{
MySurvey : <span style="color: #00aaaa;">ISurvey</span>[] = [];
<span style="color: #0000aa;">constructor</span>(<span style="color: #0000aa;">private</span> _surveyService: <span style="color: #00aaaa;">SurveyService</span>){
}
ngOnInit(){
<span style="color: #0000aa;">this</span>._surveyService.getSurveyQuestion().subscribe(data => {
console.log(data);
<span style="color: #0000aa;">this</span>.MySurvey = data;
}, err => {
console.log(err);
});
}
}
</pre>
</div>
<br />
Finally, here is our template which will be rendered as soon as data gets populated in our <strong><em>ISurvey[]</em></strong> array.
<br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;">Component({
selector: <span style="color: #aa5500;">'survey'</span>,
template: `<span style="color: dodgerblue; font-weight: bold;"><div></span>
<span style="color: dodgerblue; font-weight: bold;"><h2></span>Question : <span style="color: dodgerblue; font-weight: bold;"></h2></span>
<span style="color: dodgerblue; font-weight: bold;"><div</span> <span style="color: dodgerblue;">*ngIf=</span><span style="color: #aa5500;">"MySurvey && MySurvey.length"</span><span style="color: dodgerblue; font-weight: bold;">></span>
<span style="color: dodgerblue; font-weight: bold;"><div</span> <span style="color: dodgerblue;">*ngFor=</span><span style="color: #aa5500;">"let survey of MySurvey; let idx = index"</span><span style="color: dodgerblue; font-weight: bold;">><br/></span>
<span style="color: dodgerblue; font-weight: bold;"><div></span>{{survey.question}}<span style="color: dodgerblue; font-weight: bold;"></div></span>
<span style="color: dodgerblue; font-weight: bold;"><div</span> <span style="color: dodgerblue;">*ngFor=</span><span style="color: #aa5500;">"let choice of survey.choices"</span><span style="color: dodgerblue; font-weight: bold;">></span>
<span style="color: dodgerblue; font-weight: bold;"><input</span> <span style="color: dodgerblue;">type=</span><span style="color: #aa5500;">"radio"</span> <span style="color: dodgerblue;">name=</span><span style="color: #aa5500;">"radioGroup{{idx}}"</span><span style="color: dodgerblue; font-weight: bold;">/></span>{{choice}}
<span style="color: dodgerblue; font-weight: bold;"></div></span>
<span style="color: dodgerblue; font-weight: bold;"></div></span>
<span style="color: dodgerblue; font-weight: bold;"></div></span>
<span style="color: dodgerblue; font-weight: bold;"></div></span>
`
})
<span style="color: #0000aa;">export</span> <span style="color: #0000aa;">class</span> Survey <span style="color: #0000aa;">implements</span> OnInit{
...
}
</pre>
</div>
<br/>
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Post body ad responsive -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-4262325767595391" data-ad-format="auto" data-ad-slot="9970526860" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br/>
<h3>
The RxJS Retry operator</h3>
If your want to <strong>retry</strong> your http requests on case you receives error in your http response, then there is a retry operator (provided by RxJs) that you can use to resubscribe to the observable to re-invoke it for a number of times.
<br />
This following code will retry 3 times as http service continues to receive any http error.
<br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #0000aa;">import</span> <span style="color: #aa5500;">'rxjs/add/operator/retry'</span>;
http
.get(<span style="color: #aa5500;">'/api/questions'</span>)
.retry(<span style="color: #009999;">3</span>)
.subscribe(...);
</pre>
</div>
<br/>
You can go through the advance Http configuration and functions from the Angular's official documentation: <a href="https://angular.io/guide/http" target="_blank">https://angular.io/guide/http</a>
<br />
<h3>
Full working example here</h3>
<a href="https://embed.plnkr.co/eKil3iBwhppDNtzqf2YH/" target="_blank">https://embed.plnkr.co/eKil3iBwhppDNtzqf2YH/</a>
</div>
Satya Jugranhttp://www.blogger.com/profile/02579918194785863102noreply@blogger.com16tag:blogger.com,1999:blog-4672721440989923845.post-14754081842046770912017-09-27T11:16:00.000-07:002019-01-10T05:36:01.351-08:00Angular 5 : Life Cycle Hooks<div dir="ltr" style="text-align: left;" trbidi="on">
<img class="img img-responsive center-block" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjWw4tT2JNRDmWpHUzTVgt7S_JEoyrWilXrLCcDfogWHJX7KXvqBWGlcgPeFpVWde5ILw4OL1aLwkiMpehJhbIlftd-GQ2l4_5RJEOC1ns7Mw_WDz9qjpFTAVeD2fJNCLy5HNKIn7UGBj_g/s640/angular-lifecycle-hooks.png" /><br />
<p> <strong>Important announcement</strong> : We are moving all our content to new website - <a href="https://witscad.com/courses"> Witscad Courses </a>. You can find the updated complete Angular course here - <a href="https://witscad.com/course/complete-angular-tutorial">A Complete Angular Tutorial</a>. Feel free to visit. </p>
Every component in Angular has its own lifecycle events that occurs as the component gets created, renders, changes it's property values or gets destroyed. Angular invokes certain set of methods or we call them hooks, that gets executed as soon as those lifecycle events gets fired.
<br />
<br />
Lifecycle hooks are wrapped in certain interfaces which are included in the angular core <strong>'@angular/core'</strong> library.
<br />
<br />
One thing to note that each of these interfaces includes one method whose name is same as of the interface name but it is just prefixed by <strong>"ng"</strong>. For example <strong>OnInit</strong> interface has one method <strong>ngOnInit()</strong>.
The following lifecycle hooks are exposed by Angular corresponding to different lifecycle events.
<br />
<ul>
<li>ngOnChanges()</li>
<li>ngOnInit()</li>
<li>ngDoCheck()</li>
<li>ngAfterContentInit()</li>
<li>ngAfterContentChecked()</li>
<li>ngAfterViewInit()</li>
<li>ngAfterViewChecked()</li>
<li>ngOnDestroy()</li>
</ul>
<br />
These are pretty much well documented in Angular official documentation (<a href="https://angular.io/guide/lifecycle-hooks" target="_blank">https://angular.io/guide/lifecycle-hooks</a>) but I'll try to explain them in an easy way. Let's take one by one to understand what all these are and then we will move on to how these gets invoked.
<br />
<h2>
ngOnChanges()</h2>
It is invoked whenever an Input() property of a component gets changed. We know that if we are using an Input() decorator this means it is an input property, the value for which is going to be supplied by it's parent component. This will gets executed every time the Input() property value changes.
<br />
<h2>
ngOnInit()</h2>
The data value initializes after the component gets constructed. After this the ngOnInit() executes. This is called one time only per component creation. This is normally used to initialize any http calls or any heavy startup operations which should not be executed in constructor function.
<br />
<h2>
ngDoCheck()</h2>
Normally Angular automatically does the change detection of properties and events and updates the view or invokes any other event accordingly. But sometimes, we need to execute some functionality of keep checking certain thing on every change detection. This is where <strong>ngDoCheck()</strong> does the job for you. For example - you want to check the performance of your complex component as how many changes are happening frequently. In this case we can log things which let us know which changes and how frequently those changes are happening.
<br />
<i class="fa fa-warning" style="color: #f39c12;"></i> Please note that implementing this method is very costly as this gets executed on every change cycle. So do try to avoid it and use if it is really really required.
<br />
<br/>
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Post body ad responsive -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-4262325767595391" data-ad-format="auto" data-ad-slot="9970526860" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br/>
<h2>
ngAfterViewInit() and ngAfterViewChecked()</h2>
These are called once the child view is created.
ngAfterViewInit() is called only one time when the child view is initialized.
ngAfterViewChecked() is called whenever there is any changes that encountered in the child's view.
<br />
<i class="fa fa-warning" style="color: #f39c12;"></i> This means that both of these hooks are consumed by the parent view for the child view. <strong>ngAfterViewChecked()</strong> hook should be avoided for the same performance issue reasons.
<br />
<h2>
ngAfterContentInit() and ngAfterContentChecked()</h2>
These are similar to AfterViewInit() and AfterViewChecked() but the difference can be found from below examples:
If we normally want to render any child component, we usually place the child selector in parent template e.g:
<br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;">`<span style="color: #007700;"><div></span>
<span style="color: #007700;"><my-child></my-child></span>
<span style="color: #007700;"></div></span>`
</pre>
</div>
if we want to import some external html into our view, which may or may not be an Angular child template, then we can achieve the same through AfterContect hooks. The component have to use <ng-content> to import external html or another Angular component into the view.
</ng-content><br />
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #007700;">`<div></span>
<span style="color: #007700;"><ng-content></ng-content></span>
<span style="color: #007700;"></div>`</span>
</pre>
</div>
<h2>
ngOnDestroy()</h2>
Any clean-up logic for the component, we use to write in this hook. As soon as the component gets destroyed, this method is invoked. This is very useful and should be used to free up any global variable, temporary subscriptions or any third party initialization.
<br />
Now, we pretty much understood what these life cycle hooks are. Let's now focus on how these lifecycle hooks invoked in an Angular component lifecycle.
<br />
I have created an example - <a href="https://embed.plnkr.co/XVMd1oQfI3IjRYTkG9li/" target="_blank">https://embed.plnkr.co/XVMd1oQfI3IjRYTkG9li/</a>. Here I have created a sample Sign up form component. There is one more child component called "Random" component which is a part of Sign up form component.
<br />
This sign up form can be shown or hide from our main app.
<br />
<h3>
Signup component</h3>
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #008800; font-weight: bold;">import</span> {Component, Injectable} from <span style="background-color: #fff0f0;">'@angular/core'</span>
@Component({
selector<span style="color: #333333;">:</span> <span style="background-color: #fff0f0;">'signup'</span>,
template : `<span style="color: #007700;"><div></span>
<span style="color: #007700;"><h2></span>Name : <span style="color: #007700;"></h2></span>
<span style="color: #007700;"><input</span> <span style="color: #0000cc;">type=</span><span style="background-color: #fff0f0;">'text'</span> <span style="color: #0000cc;">[(ngModel)]=</span><span style="background-color: #fff0f0;">'name'</span> <span style="color: #007700;">/></span>
<span style="color: #007700;"><input</span> <span style="color: #0000cc;">type=</span><span style="background-color: #fff0f0;">'text'</span> <span style="color: #0000cc;">[(ngModel)]=</span><span style="background-color: #fff0f0;">'prefix'</span> <span style="color: #007700;">/></span>
<span style="color: #007700;"><random</span> <span style="color: #0000cc;">[salt]=</span><span style="background-color: #fff0f0;">'prefix'</span>
<span style="color: #0000cc;">(generatePassword)=</span><span style="background-color: #fff0f0;">'onGeneratePassword($event)'</span><span style="color: #007700;">></random></span>
<span style="color: #007700;"><h3></span>Password : {{password}}<span style="color: #007700;"></h3></span>
<span style="color: #007700;"></div></span>`
})
<span style="color: #008800; font-weight: bold;">export</span> <span style="color: #008800; font-weight: bold;">class</span> Signup <span style="color: #008800; font-weight: bold;">implements</span> OnInit, OnChanges, DoCheck, AfterViewChecked, AfterViewInit, AfterContentInit, AfterContentChecked, OnDestroy{
name:<span style="color: #333399; font-weight: bold;">string</span> <span style="color: #333333;">=</span> <span style="background-color: #fff0f0;">'Angular'</span>;
prefix:<span style="color: #333399; font-weight: bold;">string</span> <span style="color: #333333;">=</span> <span style="background-color: #fff0f0;">''</span>;
password: <span style="color: #333399; font-weight: bold;">string</span> <span style="color: #333333;">=</span> <span style="background-color: #fff0f0;">''</span>;
<span style="color: #008800; font-weight: bold;">constructor</span>(){
<span style="color: #008800; font-weight: bold;">this</span>.name <span style="color: #333333;">=</span> <span style="background-color: #fff0f0;">'Angular 2'</span>;
}
onGeneratePassword(pwd: <span style="color: #333399; font-weight: bold;">string</span>){
<span style="color: #008800; font-weight: bold;">this</span>.password <span style="color: #333333;">=</span> pwd;
}
ngOnInit(){
<span style="color: #008800; font-weight: bold;">this</span>.name <span style="color: #333333;">=</span> <span style="background-color: #fff0f0;">'Angular 5'</span>;
console.log(<span style="background-color: #fff0f0;">'Parent ngOnInit() called'</span>);
}
ngOnChanges(){
console.log(<span style="background-color: #fff0f0;">'Parent ngOnChanges() called'</span>);
}
ngDoCheck(){
console.log(<span style="background-color: #fff0f0;">'Parent ngDoCheck() called'</span>)
}
ngAfterViewChecked(){
console.log(<span style="background-color: #fff0f0;">'Parent AfterViewChecked() called'</span>);
}
ngAfterViewInit(){
console.log(<span style="background-color: #fff0f0;">'Parent ngAfterViewInit() called'</span>);
}
ngAfterContentInit(){
console.log(<span style="background-color: #fff0f0;">'Parent ngAfterContentInit() called'</span>);
}
ngAfterContentChecked(){
console.log(<span style="background-color: #fff0f0;">'Parent ngAfterContentChecked() called'</span>);
}
ngOnDestroy(){
console.log(<span style="background-color: #fff0f0;">'Parent ngOnDestroy() called'</span>);
}
}
</pre>
</div>
<br/>
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Post body ad responsive -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-4262325767595391" data-ad-format="auto" data-ad-slot="9970526860" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br/>
<h3>
Random password generator component:</h3>
<!-- HTML generated using hilite.me -->
<div style="background: #ffffff; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #008800; font-weight: bold;">import</span> {Component, Injectable, Input, Output, EventEmitter} from <span style="background-color: #fff0f0;">'@angular/core'</span>
@Component({
selector<span style="color: #333333;">:</span> <span style="background-color: #fff0f0;">'random'</span>,
template: `<span style="color: #333333;"><</span>div<span style="color: #333333;">></span>
<span style="color: #333333;"><</span>input type<span style="color: #333333;">=</span><span style="background-color: #fff0f0;">'button'</span> (click)<span style="color: #333333;">=</span><span style="background-color: #fff0f0;">'random()'</span> value<span style="color: #333333;">=</span><span style="background-color: #fff0f0;">'Generate Password'</span> <span style="color: #333333;">/></span>
<span style="color: #333333;"></div></span>`
})
<span style="color: #008800; font-weight: bold;">export</span> <span style="color: #008800; font-weight: bold;">class</span> Random <span style="color: #008800; font-weight: bold;">implements</span> OnInit, OnChanges, DoCheck, AfterViewChecked, AfterViewInit, AfterContentInit, AfterContentChecked, OnDestroy{
@Input() salt:<span style="color: #333399; font-weight: bold;">string</span>;
@Output() generatePassword: <span style="color: #333399; font-weight: bold;">EventEmitter</span><span style="color: #333333;"><</span><span style="color: #333399; font-weight: bold;">string</span><span style="color: #333333;">></span> <span style="color: #333333;">=</span> <span style="color: #008800; font-weight: bold;">new</span> EventEmitter<span style="color: #333333;"><</span><span style="color: #333399; font-weight: bold;">string</span><span style="color: #333333;">></span>();
<span style="color: #008800; font-weight: bold;">constructor</span>(){
<span style="color: #008800; font-weight: bold;">this</span>.salt <span style="color: #333333;">=</span> <span style="background-color: #fff0f0;">''</span>;
}
random(){
<span style="color: #008800; font-weight: bold;">var</span> t <span style="color: #333333;">=</span> <span style="color: #008800; font-weight: bold;">new</span> <span style="color: #007020;">Date</span>().getTime();
<span style="color: #008800; font-weight: bold;">this</span>.generatePassword.emit(<span style="color: #008800; font-weight: bold;">this</span>.salt <span style="color: #333333;">+</span> t.toString());
}
ngOnInit(){
console.log(<span style="background-color: #fff0f0;">'Child ngOnInit() called'</span>);
}
ngOnChanges(){
console.log(<span style="background-color: #fff0f0;">'Child ngOnChanges() called'</span>);
}
ngDoCheck(){
console.log(<span style="background-color: #fff0f0;">'Child ngDoCheck() called'</span>);
}
ngAfterViewChecked(){
console.log(<span style="background-color: #fff0f0;">'Child AfterViewChecked() called'</span>);
}
ngAfterViewInit(){
console.log(<span style="background-color: #fff0f0;">'Child ngAfterViewInit() called'</span>);
}
ngAfterContentInit(){
console.log(<span style="background-color: #fff0f0;">'Child ngAfterContentInit() called'</span>);
}
ngAfterContentChecked(){
console.log(<span style="background-color: #fff0f0;">'Child ngAfterContentChecked() called'</span>);
}
ngOnDestroy(){
console.log(<span style="background-color: #fff0f0;">'Child ngOnDestroy() called'</span>);
}
}
</pre>
</div>
<br/>
As your can see, we have captured all events of child and parent component to showcase how they are getting invoked and at what sequence of component's life cycle. Here is the output on click of <strong>"Show Signup"</strong>. Let's discuss this:<br />
<div>
<br /></div>
<div>
<img class="img img-responsive center-block" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiD5zsSndmSbexLt5w_Yn8dmMJkPhKZtAGI8aaEhBsUE_e5HLSAqzKUf4QL5dDuwY9rCf49G7-lbthrKpr1QSKWrFITj7pVZKfQW_HzmWJ4DKzBNgasNaztFHZLh97d-HmlXpWhwutLBdj7/s640/angular-lifecycle.JPG" /><br />
First and foremost, parent and child component gets constructed. The parent component initialization happens.
<br />
<br />
Just after <strong>ngOnInit()</strong> and <strong>ngDoCheck()</strong>, <strong>AfterContent</strong> is getting called. This means that any external html is first compiled into the view. After this the child component starts initializing. As discussed earlier as well that <strong>ngOnChanges()</strong> will be invoked whenever any child's Input() property is getting initialized or changed.
<br />
<br />
Now, if we closely look, Child's AfterView hooks are called first. This means the child will prepare it's complete template before handing it over to the parent.
After that the Parent's AfterView hooks are called because parent now rely on the fact that it's own view is complete because it's child views were completed.
<br />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Post body ad responsive -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-4262325767595391" data-ad-format="auto" data-ad-slot="9970526860" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br />
After clicking <strong>"Hide Signup"</strong>, the parent component will be removed because of <strong>*ngIf</strong>. This means all it's child components will also be destroyed as well. Here is the output of this click:<br />
<pre></pre>
<pre><img class="img img-responsive center-block" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg9d8JFaACErj-3GQcfDgBje2OtsaQjK-JpsMAlgmd_TdM2jhyGZybmzrysFjzjPmc4Oe2sM5Rwkw9w6vq0Zi0uOV21wuYIbXDj822afWLreazwu-gCgXQz0mJYbBAQU0IS-tPs0Si2oBk5/s640/components-destroy.JPG" /></pre>
<pre>
</pre>
This indicates that the child component clean-up will be done first and then parent component clean-up will be executed.
<br /><br/>
There is one catch left in this example, if you see that for both parent and child component <strong>AfterContentChecked</strong> and <strong>AfterViewChecked</strong> are getting called twice. <br/><strong>Why is that?</strong> It's for you folks, let's put your comments below to explain what is the catch here.
</div>
</div>
Satya Jugranhttp://www.blogger.com/profile/02579918194785863102noreply@blogger.com1tag:blogger.com,1999:blog-4672721440989923845.post-41191304516949101342017-09-23T13:54:00.000-07:002019-01-10T05:36:09.678-08:00Angular 5 : Services and Dependency Injection<div dir="ltr" style="text-align: left;" trbidi="on">
<img class="img img-responsive center-block" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWgzXUfiTw281VX2mwNmIjJwpkwCuZb19nIP9FWOnQ5N40IF5_U4uYEmzrKd2itGAPa6S521KS2WCmX-cZbKYLZbAJRVSUyaY6faufufJqI7SFznG1Ev2U1zEe2mqygSqc70cTRSby9rWC/s640/angular-services-and-dependency-injection.JPG" /><br />
<p> <strong>Important announcement</strong> : We are moving all our content to new website - <a href="https://witscad.com/courses"> Witscad Courses </a>. You can find the updated complete Angular course here - <a href="https://witscad.com/course/complete-angular-tutorial">A Complete Angular Tutorial</a>. Feel free to visit. </p>
Let's look some definitions to understand the subject.<br />
<br />
A <span style="font-size: x-large;">Service </span>is a functionality that can be shared with different Components. Whenever we find some common aspects in our components, we usually separate it out as a Service.<br />
<br />
<span style="font-size: x-large;">Dependency Injection</span> is a coding pattern in which a class takes the instances of objects it needs which is called dependencies from an external source rather than creating them itself.<br />
<br />
In Angular, services are Singleton. It internally implements the Service Locator Pattern. This means each service register itself under one container as a single instance. Angular provides a built in Injector which acts as a container to hold the single instances of all registered services. Angular takes care of creation of Service instance and registering it to the Service container.<br />
<br />
<h2 style="text-align: left;">
The @Injectable() decorator</h2>
To inject the service into component, Angular provides an Injector decorator : @Injectable().<br />
<br />
<h3 style="text-align: left;">
We broadly have the following steps to create a Service:</h3>
1) Create the service class<br />
2) Define the metadata with a decorator<br />
3) Import what we need.<br />
<br />
<br />
To understand the Service more, let's built a service in Angular for getting the user profile details in the User component. Let's create some classes:<br />
<h4 style="text-align: left;">
1. IProfile interface</h4>
<div style="background: #f0f0f0; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #007020; font-weight: bold;">export</span> <span style="color: #007020; font-weight: bold;">interface</span> IProfile{
Name: <span style="color: #902000;">string</span>;
Age: <span style="color: #902000;">number</span>;
}
</pre>
</div>
<div>
<br />
<h4 style="text-align: left;">
2. Profile Class</h4>
</div>
<div style="background: #f0f0f0; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #007020; font-weight: bold;">import</span> {Component, Injectable} from <span style="color: #4070a0;">'@angular/core'</span>
<span style="color: #007020; font-weight: bold;">import</span> {IProfile} from <span style="color: #4070a0;">'./iprofile'</span>
@Component({
selector<span style="color: #666666;">:</span> <span style="color: #4070a0;">'profile'</span>,
template<span style="color: #666666;">:</span> `
<span style="color: #666666;"><</span>div<span style="color: #666666;">></span>
<span style="color: #666666;"><</span>h2<span style="color: #666666;">></span>Name <span style="color: #666666;">:</span> {{MyProfile.Name}}<span style="color: #666666;"><</span>/h2>
<span style="color: #666666;"><</span>h2<span style="color: #666666;">></span>Age <span style="color: #666666;">:</span> {{MyProfile.Age}}<span style="color: #666666;"><</span>/h2>
<span style="color: #666666;"><</span>/div>
`
})
<span style="color: #007020; font-weight: bold;">export</span> <span style="color: #007020; font-weight: bold;">class</span> Profile{
MyProfile : <span style="color: #902000;">IProfile</span>;
<span style="color: #007020; font-weight: bold;">constructor</span>(){
}
}
</pre>
</div>
<br />
<h4 style="text-align: left;">
3. ProfileService class</h4>
<div style="background: #f0f0f0; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #007020; font-weight: bold;">import</span> {Injectable} from <span style="color: #4070a0;">'@angular/core'</span>
<span style="color: #007020; font-weight: bold;">import</span> {IProfile} from <span style="color: #4070a0;">'./iprofile'</span>
@Injectable()
<span style="color: #007020; font-weight: bold;">export</span> <span style="color: #007020; font-weight: bold;">class</span> ProfileService{
getProfiles()<span style="color: #666666;">:</span> IProfile[]{
<span style="color: #007020; font-weight: bold;">return</span> [{
Name<span style="color: #666666;">:</span><span style="color: #4070a0;">'Bob'</span>,
Age: <span style="color: #902000;">25</span>
},
{
Name<span style="color: #666666;">:</span><span style="color: #4070a0;">'Alice'</span>,
Age: <span style="color: #902000;">23</span>
}];
}
}
</pre>
</div>
<br />
<br />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Post body ad responsive -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-4262325767595391" data-ad-format="auto" data-ad-slot="9970526860" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br />
<h2 style="text-align: left;">
Registering a Service:</h2>
A Service can be registered in any component. However, it should be registered at root level component only. This is because it we register at two different nested level component, then the service will have two entire different instances in both components. However, we can register at any nested level component just in case if we require to use the service in that component or it's child components only.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjNBITR-vvIMvx7CbOCGCGMjOEYTrgr5-pquQUeoZE8abieFa6LyWX7pnURGxZd2iY5-hm4ZdeEX3x7kTU27nmTDi0iH2UO7HTPimLuHBq7m8IDvx_0PTPOZpHONXGOG63rKazx3Hj3TytI/s1600/DependencyInjection1.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="356" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjNBITR-vvIMvx7CbOCGCGMjOEYTrgr5-pquQUeoZE8abieFa6LyWX7pnURGxZd2iY5-hm4ZdeEX3x7kTU27nmTDi0iH2UO7HTPimLuHBq7m8IDvx_0PTPOZpHONXGOG63rKazx3Hj3TytI/s640/DependencyInjection1.png" width="640" /></a></div>
<br />
In above figure, <br />
1. The "Service 1" is registered at app level, so it is available to all the nested components.<br />
2. The "Service 2" is registered at "Parent 1" component, so it is available to Parent 1, Child1, Child2 and Child 3 components.<br />
3. The "Service 3" is registered at "Child 1" component, so it is available to "Child 1" only, as no other component comes under its hierarchy.<br />
4. The "Service 4" is registered at "Parent 2" component, so it is available to Parent 2 and Child 4 only.<br />
<br />
Now, if we try to register "Service 1" both in root component and "Parent 1" component, then it's two instances will be created. That is why, we should register the service at an appropriate component level as per it's usage.<br />
<br />
Continuing with our example, Import ProfileService and change the @NgModule() decorator of root level component as:<br />
<br />
<div style="background: #f0f0f0; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #007020; font-weight: bold;">import</span> {ProfileService} from <span style="color: #4070a0;">'./profile.service'</span>;
.
.
.
@NgModule({
imports<span style="color: #666666;">:</span> [ BrowserModule ],
declarations<span style="color: #666666;">:</span> [ App ],
providers<span style="color: #666666;">:</span>[ProfileService],
bootstrap<span style="color: #666666;">:</span> [ App ]
})
</pre>
</div>
<br />
<br />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Post body ad responsive -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-4262325767595391" data-ad-format="auto" data-ad-slot="9970526860" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br />
<br />
<h2 style="text-align: left;">
Injecting a Service in component:</h2>
<div>
We can inject our service as a parameter to our constructor class.<br />
<br /></div>
<div style="background: #f0f0f0; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #007020; font-weight: bold;">constructor</span>(<span style="color: #007020; font-weight: bold;">private</span> _profileService: <span style="color: #902000;">ProfileService</span>){
}
</pre>
</div>
<br />
Now, we can execute the methods of our service to get the data. We can call the service method inside our constructor, but what if the service wants to pull to data from backend. We don't want the construction of our class halted till the time we pull the data.<br />
A better solution would be to implement the <i>OnInit </i>interface hook provided by Angular and call the service method inside <i>ngOnInit</i>() function. (Know more about Angular hooks here.)<br />
<br />
Modify the Profile class as below:<br />
<br />
<div style="background: #f0f0f0; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #007020; font-weight: bold;">import</span> {Component, Injectable} from <span style="color: #4070a0;">'@angular/core'</span>
<span style="color: #007020; font-weight: bold;">import</span> {ProfileService} from <span style="color: #4070a0;">'./profile.service'</span>;
<span style="color: #007020; font-weight: bold;">import</span> {IProfile} from <span style="color: #4070a0;">'./iprofile'</span>
@Component({
selector<span style="color: #666666;">:</span> <span style="color: #4070a0;">'profile'</span>,
template<span style="color: #666666;">:</span> `
<span style="color: #666666;"><</span>div<span style="color: #666666;">></span>
<span style="color: #666666;"><</span>h2<span style="color: #666666;">></span>Name <span style="color: #666666;">:</span> {{MyProfile.Name}}<span style="color: #666666;"><</span>/h2>
<span style="color: #666666;"><</span>h4<span style="color: #666666;">></span>Age <span style="color: #666666;">:</span> {{MyProfile.Age}}<span style="color: #666666;"><</span>/h4>
<span style="color: #666666;"><</span>/div>
`,
})
<span style="color: #007020; font-weight: bold;">export</span> <span style="color: #007020; font-weight: bold;">class</span> Profile <span style="color: #007020; font-weight: bold;">implements</span> OnInit{
ProfileList : <span style="color: #902000;">IProfile</span>[];
MyProfile : <span style="color: #902000;">IProfile</span>;
<span style="color: #007020; font-weight: bold;">constructor</span>(<span style="color: #007020; font-weight: bold;">private</span> _profileService: <span style="color: #902000;">ProfileService</span>){
}
ngOnInit(){
<span style="color: #007020; font-weight: bold;">this</span>.ProfileList <span style="color: #666666;">=</span> <span style="color: #007020; font-weight: bold;">this</span>._profileService.getProfiles();
<span style="color: #007020; font-weight: bold;">this</span>.MyProfile <span style="color: #666666;">=</span> <span style="color: #007020; font-weight: bold;">this</span>.ProfileList[<span style="color: #40a070;">0</span>];
}
}
</pre>
</div>
<br />
<br />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Post body ad responsive -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-4262325767595391" data-ad-format="auto" data-ad-slot="9970526860" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br />
<br />
<h2 style="text-align: left;">
To summarize:</h2>
* Create a Service class<br />
* Use @Injectable() decorator to the service.<br />
* Register the service at the root component.<br />
* Inject the service as a constructor parameter of the dependent class.<br />
<br />
<h2 style="text-align: left;">
Live Code:</h2>
Plunker here:
<a href="https://embed.plnkr.co/SbgOOoUtJIeaQBY2FizW?show=app,preview">https://embed.plnkr.co/SbgOOoUtJIeaQBY2FizW?show=app,preview</a>
</div>
Satya Jugranhttp://www.blogger.com/profile/02579918194785863102noreply@blogger.com0tag:blogger.com,1999:blog-4672721440989923845.post-13465840217086232302017-09-23T13:51:00.000-07:002019-01-10T05:36:55.038-08:00Angular 5 : Working with Nested Components<div dir="ltr" style="text-align: left;" trbidi="on">
<img class="img img-responsive center-block" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgRntBp8lStrVsD568jNUZYTW-sdklag9MmrxbMMst80x3kJjFiU_cawDh_CF0r9GMaKyLqAWk5SrrDjgfYv57AfKY5XIXVP71wcw_7QS2rHsieFft338nWAa8YP3uGKj0isPLuJcfthP4Y/s640/angular-working-with-nested-components.JPG" />
<br/>
<p> <strong>Important announcement</strong> : We are moving all our content to new website - <a href="https://witscad.com/courses"> Witscad Courses </a>. You can find the updated complete Angular course here - <a href="https://witscad.com/course/complete-angular-tutorial">A Complete Angular Tutorial</a>. Feel free to visit. </p>
<h2 style="text-align: left;">
What are Nested/Child components?</h2>
<div>
<div>
A Component in Angular can have child components. Also, those child components can have their own further child components. Angular seamlessly supports nested components.</div>
<div>
<br /></div>
<div>
As an example, consider a calculator as a top level component. It is built with several other child components like screen component, button component, body component, battery component etc. These screen, button, body and battery components are nested components of Calculator component.</div>
<div>
<br /></div>
<div>
The nested component have all the functionalities just as any other Angular component.</div>
<div>
<h4 style="text-align: left;">
Now several question arises in our mind:</h4>
</div>
<div class="row">
<div class="col-xs-2 col-sm-3 col-md-3 col-lg-3">
<img class="img-responsive center-block" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEid9sIezy4NDTDByhvPs1_C_B4KnohbvlyZP3Za-KBYMzbC1z2hawN9P6XmAftQFJhS2Y-LndCfC_qg1tAsFUBmuFKsXxNxOyJXYBD-uy6yX8yc2PTwMjaFg02DIqSmVDbppc1fdfR6SEVA/s320/person-thinking.jpg" />
</div>
<div class="col-xs-10 col-sm-9 col-md-9 col-lg-9">
<ol>
<li>How we are going to use our nested components in its parent component?</li>
<li>How we can pass data from parent component into its child component?</li>
<li>How can we get the data back from child component to parent component?</li>
<li>How does the child component can respond to the parent events?</li>
<li>How does the parent component can respond to the child events?</li>
</ol>
</div>
</div>
<br />
<div>
To answer all these questions, lets us built a step-by-step example where we have a profile page of a person. It will also have a friend's list.</div>
<div>
<br /></div>
<h2 style="text-align: left;">
1) Building Parent and Child components.</h2>
<div>
Let's first built our Child component in our example app which is Friend list component.<br />
<br /></div>
<div style="background: #f0f0f0; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #007020; font-weight: bold;">import</span> { Component } from <span style="color: #4070a0;">'@angular/core'</span>;
@Component({
selector<span style="color: #666666;">:</span> <span style="color: #4070a0;">'my-friends'</span>,
template<span style="color: #666666;">:</span> `<span style="color: #666666;"><</span>div<span style="color: #666666;">></span>
<span style="color: #666666;"><</span>table<span style="color: #666666;">></span>
<span style="color: #666666;"><</span>tr <span style="color: #666666;">*</span>ngFor<span style="color: #666666;">=</span><span style="color: #4070a0;">'let friend of friends'</span><span style="color: #666666;">></span>
<span style="color: #666666;"><</span>td<span style="color: #666666;">></span>{{friend}}<span style="color: #666666;"><</span>/td>
<td<span style="color: #666666;">></span>
<span style="color: #666666;"><</span>img
src<span style="color: #666666;">=</span><span style="color: #4070a0;">"http://witspry.in/ContentServer/Images/User/user.png"</span>
width<span style="color: #666666;">=</span><span style="color: #4070a0;">"20"</span> <span style="color: #666666;">/></span>
<span style="color: #666666;"><</span>/td>
<span style="color: #666666;"><</span>/tr>
<span style="color: #666666;"><</span>/table>
<span style="color: #666666;"><</span>/div>`
})
<span style="color: #007020; font-weight: bold;">export</span> <span style="color: #007020; font-weight: bold;">class</span> MyFriendsComponent{
friends: <span style="color: #902000;">Array</span><span style="color: #666666;"><</span><span style="color: #902000;">string</span><span style="color: #666666;">></span> <span style="color: #666666;">=</span> [
<span style="color: #4070a0;">'Friend 1'</span>,
<span style="color: #4070a0;">'Friend 2'</span>,
<span style="color: #4070a0;">'Friend 3'</span>,
<span style="color: #4070a0;">'Friend 4'</span>,
<span style="color: #4070a0;">'Friend 5'</span>,
];
}
</pre>
</div>
<br />
Now, let's built our Parent component which is User's profile page.<br />
<br />
<div style="background: #f0f0f0; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #007020; font-weight: bold;">import</span> { Component } from <span style="color: #4070a0;">'@angular/core'</span>;
<span style="color: #007020; font-weight: bold;">import</span> {MyFriendsComponent} from <span style="color: #4070a0;">'./myFriends'</span>;
@Component({
selector<span style="color: #666666;">:</span> <span style="color: #4070a0;">'my-profile'</span>,
template<span style="color: #666666;">:</span>`<span style="color: #666666;"><</span>img [src]<span style="color: #666666;">=</span><span style="color: #4070a0;">"imgURL"</span> width<span style="color: #666666;">=</span><span style="color: #4070a0;">"50"</span><span style="color: #666666;">/></span>
<span style="color: #666666;"><</span>h3<span style="color: #666666;">></span>My Friends<span style="color: #666666;"><</span>/h3>
<span style="color: #666666;"><</span>my<span style="color: #666666;">-</span>friends<span style="color: #666666;">><</span>/my-friends>`
})
<span style="color: #007020; font-weight: bold;">export</span> <span style="color: #007020; font-weight: bold;">class</span> MyProfileComponent{
<span style="color: #007020; font-weight: bold;">constructor</span>(){
<span style="color: #007020; font-weight: bold;">this</span>.imgURL <span style="color: #666666;">=</span> <span style="color: #4070a0;">'http://witspry.in/ContentServer/Images/User/user_circle.png'</span>;
}
}
</pre>
</div>
<br />
* See the above example as how the <my-friends> is used as a directive to the Profile component.<br />
<br />
Now, in main app import both component and add them in the "declarations" array.<br />
<br />
<div style="background: #f0f0f0; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;">@NgModule({
imports<span style="color: #666666;">:</span> [ BrowserModule ],
declarations<span style="color: #666666;">:</span> [ App, MyProfileComponent, MyFriendsComponent ],
bootstrap<span style="color: #666666;">:</span> [ App ]
})
<span style="color: #007020; font-weight: bold;">export</span> <span style="color: #007020; font-weight: bold;">class</span> AppModule {}
</pre>
</div>
<br />
<br />
Next, we are going to see how parent component provides input to child component and how child component emit events to send the payloads to parent component. Here is a diagram to get a gist of it.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh3ryZSHs2rau8M8LA1H5POAfgBJ7Zos935LYlpB8kp28yrZxx9D6vq76vEBN9eB2YeAj5r9coec-2iMFsCI0w1nj04SZptDk5PWjYv3C4vvy6uzS2KkFT-B8SV4xFsUHu7cmP59JuNa_jT/s1600/NestedComponentsOverview.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="480" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh3ryZSHs2rau8M8LA1H5POAfgBJ7Zos935LYlpB8kp28yrZxx9D6vq76vEBN9eB2YeAj5r9coec-2iMFsCI0w1nj04SZptDk5PWjYv3C4vvy6uzS2KkFT-B8SV4xFsUHu7cmP59JuNa_jT/s640/NestedComponentsOverview.png" width="640" /></a></div>
<br />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Post body ad responsive -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-4262325767595391" data-ad-format="auto" data-ad-slot="9970526860" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br />
<h2 style="text-align: left;">
2) Passing data using @Input() decorator.</h2>
@Input() decorator to the rescue<br />
<br />
Add a variable name as a following line with @Input() decorator.<br />
<br />
<div style="background: #f0f0f0; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #007020; font-weight: bold;">export</span> <span style="color: #007020; font-weight: bold;">class</span> MyFriendComponent{
@Input() name : <span style="color: #902000;">string</span>;
}
</pre>
</div>
<br />
Change our User's profile page as:<br />
<br />
<div style="background: #f0f0f0; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;">@Component({
selector<span style="color: #666666;">:</span> <span style="color: #4070a0;">'my-profile'</span>,
template<span style="color: #666666;">:</span>`
<span style="color: #666666;"><</span>img [src]<span style="color: #666666;">=</span><span style="color: #4070a0;">"imgURL"</span> width<span style="color: #666666;">=</span><span style="color: #4070a0;">"50"</span><span style="color: #666666;">/></span>
<span style="color: #666666;"><</span>h3<span style="color: #666666;">></span>My Friends<span style="color: #666666;"><</span>/h3>
<span style="color: #666666;"><</span>div <span style="color: #666666;">*</span>ngFor<span style="color: #666666;">=</span><span style="color: #4070a0;">"let friend of friends"</span><span style="color: #666666;">></span>
<span style="color: #666666;"><</span>my<span style="color: #666666;">-</span>friend [name]<span style="color: #666666;">=</span><span style="color: #4070a0;">'friend'</span><span style="color: #666666;">></my-friend></span>
<span style="color: #666666;"><</span>/div>
`
})
<span style="color: #007020; font-weight: bold;">export</span> <span style="color: #007020; font-weight: bold;">class</span> MyProfileComponent{
<span style="color: #007020; font-weight: bold;">constructor</span>(){
<span style="color: #007020; font-weight: bold;">this</span>.imgURL <span style="color: #666666;">=</span> <span style="color: #4070a0;">'http://witspry.in/ContentServer/Images/User/user_circle.png'</span>;
<span style="color: #007020; font-weight: bold;">this</span>.friends <span style="color: #666666;">=</span> [
<span style="color: #4070a0;">'Friend 1'</span>,
<span style="color: #4070a0;">'Friend 2'</span>,
<span style="color: #4070a0;">'Friend 3'</span>,
<span style="color: #4070a0;">'Friend 4'</span>,
<span style="color: #4070a0;">'Friend 5'</span>
];
}
}
</pre>
</div>
<br />
See the line - <i><my-friend [name]='friend'></my-friend></i><br />
Here we are passing a friend name to the "name" property of the child component.<br />
<br />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Post body ad responsive -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-4262325767595391" data-ad-format="auto" data-ad-slot="9970526860" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br/>
<h2 style="text-align: left;">
3) Raising an event using @Output() decorator</h2>
<div>
<div>
The @Output directive enables a child component to use its properties in the parent component.</div>
<div>
<br /></div>
<div>
Lets modify our MyFriend component as:</div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<div style="background: #f0f0f0; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #007020; font-weight: bold;">import</span> { Component, Input, Output, EventEmitter } from <span style="color: #4070a0;">'@angular/core'</span>;
@Component({
selector<span style="color: #666666;">:</span> <span style="color: #4070a0;">'my-friend'</span>,
template<span style="color: #666666;">:</span> `<span style="color: #666666;"><</span>div<span style="color: #666666;">></span>
<span style="color: #666666;"><</span>table<span style="color: #666666;">></span>
<span style="color: #666666;"><</span>tr<span style="color: #666666;">></span>
<span style="color: #666666;"><</span>td<span style="color: #666666;">></span>{{name}}<span style="color: #666666;"><</span>/td>
<span style="color: #666666;"><</span>td<span style="color: #666666;">></span>
<span style="color: #666666;"><</span>img src<span style="color: #666666;">=</span><span style="color: #4070a0;">"http://putiw.xyz/clashroyaleunlimitedgems/img/user.png"</span>
width<span style="color: #666666;">=</span><span style="color: #4070a0;">"20"</span> <span style="color: #666666;">/></span>
<span style="color: #666666;"> <</span>/td>
<span style="color: #666666;"><</span>td<span style="color: #666666;">><</span>button (click)<span style="color: #666666;">=</span><span style="color: #4070a0;">'OnClick()'</span><span style="color: #666666;">></span>Ping<span style="color: #666666;"><</span>/button></td>
<span style="color: #666666;"><</span>td<span style="color: #666666;">></span> {{timesPinged}} <span style="color: #666666;"><</span>/td>
<span style="color: #666666;"><</span>/tr>
<span style="color: #666666;"><</span>/table>
<span style="color: #666666;"><</span>/div>`
})
<span style="color: #007020; font-weight: bold;">export</span> <span style="color: #007020; font-weight: bold;">class</span> MyFriendComponent{
@Input() name : <span style="color: #902000;">string</span>;
timesPinged: <span style="color: #902000;">number</span> <span style="color: #666666;">=</span> <span style="color: #40a070;">0</span>;
@Output() pingClicked: <span style="color: #902000;">EventEmitter</span><span style="color: #666666;"><</span><span style="color: #902000;">string</span><span style="color: #666666;">></span> <span style="color: #666666;">=</span> <span style="color: #007020; font-weight: bold;">new</span> EventEmitter<span style="color: #666666;"><</span><span style="color: #902000;">string</span><span style="color: #666666;">></span>();
OnClick(){
<span style="color: #007020; font-weight: bold;">this</span>.timesPinged<span style="color: #666666;">++</span>;
<span style="color: #007020; font-weight: bold;">this</span>.pingClicked.emit(<span style="color: #4070a0;">'You pinged '</span> <span style="color: #666666;">+</span> <span style="color: #007020; font-weight: bold;">this</span>.name <span style="color: #666666;">+</span> <span style="color: #4070a0;">' '</span> <span style="color: #666666;">+</span>
<span style="color: #007020; font-weight: bold;"> this</span>.timesPinged <span style="color: #666666;">+</span> (<span style="color: #007020; font-weight: bold;">this</span>.timesPinged <span style="color: #666666;">==</span> <span style="color: #40a070;">1</span><span style="color: #666666;">?</span> <span style="color: #4070a0;">' time'</span> <span style="color: #666666;">:</span> <span style="color: #4070a0;">' times'</span>));
}
}
</pre>
</div>
<br />
Here, we have imported <i>Output </i>and <i>EventEmitter </i>from Angular core library. Also, we have defined an event using <i>@Output()</i> decorator. The <i>OnClick </i>is a local function which is invoked from button's click event. Since the "<i>pingClicked</i>" is decorated with @<i>Output()</i>, it's emit function is able to notify the parent component.<br />
<br />
Now, change the parent component to capture the raised event from it's child component as below:<br />
<br />
<div style="background: #f0f0f0; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #007020; font-weight: bold;">import</span> { Component } from <span style="color: #4070a0;">'@angular/core'</span>;
@Component({
selector<span style="color: #666666;">:</span> <span style="color: #4070a0;">'my-profile'</span>,
template<span style="color: #666666;">:</span> `
<span style="color: #666666;"><</span>img [src]<span style="color: #666666;">=</span><span style="color: #4070a0;">"imgURL"</span> width<span style="color: #666666;">=</span><span style="color: #4070a0;">"50"</span><span style="color: #666666;">/></span>
<span style="color: #666666;"><</span>br <span style="color: #666666;">/></span>
{{pingMessage}}
<span style="color: #666666;"><</span>br <span style="color: #666666;">/></span>
Total Pings today <span style="color: #666666;">:</span> {{totalPings}}
<span style="color: #666666;"><</span>h3<span style="color: #666666;">></span>My Friends<span style="color: #666666;"><</span>/h3>
<span style="color: #666666;"><</span>div <span style="color: #666666;">*</span>ngFor<span style="color: #666666;">=</span><span style="color: #4070a0;">"let friend of friends"</span><span style="color: #666666;">></span>
<span style="color: #666666;"><</span>my<span style="color: #666666;">-</span>friend [name]<span style="color: #666666;">=</span><span style="color: #4070a0;">'friend'</span>
(pingClicked)<span style="color: #666666;">=</span><span style="color: #4070a0;">'onFriendPingClicked($event)'</span><span style="color: #666666;">></span>
<span style="color: #666666;"><</span>/my-friend>
<span style="color: #666666;"><</span>/div>
`
})
<span style="color: #007020; font-weight: bold;">export</span> <span style="color: #007020; font-weight: bold;">class</span> MyProfileComponent{
<span style="color: #007020; font-weight: bold;">constructor</span>(){
<span style="color: #007020; font-weight: bold;">this</span>.imgURL <span style="color: #666666;">=</span>
<span style="color: #4070a0;">'http://witspry.in/ContentServer/Images/User/user_circle.png'</span>;
<span style="color: #007020; font-weight: bold;">this</span>.friends <span style="color: #666666;">=</span> [
<span style="color: #4070a0;">'Friend A'</span>,
<span style="color: #4070a0;">'Friend B'</span>,
<span style="color: #4070a0;">'Friend C'</span>,
<span style="color: #4070a0;">'Friend D'</span>,
<span style="color: #4070a0;">'Friend E'</span>
];
<span style="color: #007020; font-weight: bold;">this</span>.totalPings <span style="color: #666666;">=</span> <span style="color: #40a070;">0</span>;
<span style="color: #007020; font-weight: bold;">this</span>.pingMessage <span style="color: #666666;">=</span> <span style="color: #4070a0;">''</span>;
}
onFriendPingClicked(pingMessage: <span style="color: #902000;">string</span>)<span style="color: #666666;">:</span> <span style="color: #007020; font-weight: bold;">void</span>{
<span style="color: #007020; font-weight: bold;">this</span>.totalPings<span style="color: #666666;">++</span>;
<span style="color: #007020; font-weight: bold;">this</span>.pingMessage <span style="color: #666666;">=</span> pingMessage;
}
}
</pre>
</div>
<br />
<span style="font-size: large;">Finally</span>, we have added an Event binding (please check our previous article in Angular 5 : Data & Event bindings) which is "pingClicked". Have you remember, this was decorated with @Output in our child component. Yes, this is how was are able to use it here. Also, it is assigned to a function "onFriendPingClicked($event)". The $event contains the data that the child component emits on the occurrence of it's event.<br />
<br />
<br />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Post body ad responsive -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-4262325767595391" data-ad-format="auto" data-ad-slot="9970526860" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br/>
<h3 style="text-align: left;">
To Summarize:</h3>
* Use @Input() decorator to pass data to child component.<br />
* Use @Output() decorator to raise an event to parent component. Note : The @Output() decorator property can be only of EventEmitter type.<br />
<br />
<h2 style="text-align: left;">
Live Code</h2>
<div>
Plunker here:
<a href="https://embed.plnkr.co/nmtTHLz0vNu0HTaywwCB?amp;show=app,preview">https://embed.plnkr.co/nmtTHLz0vNu0HTaywwCB?amp;show=app,preview</a>
</div>
</div>
</div>
Satya Jugranhttp://www.blogger.com/profile/02579918194785863102noreply@blogger.com0tag:blogger.com,1999:blog-4672721440989923845.post-43442820294459937732017-09-23T13:47:00.001-07:002019-01-10T05:37:18.136-08:00Angular 5 : Builtin, Async and Custom Pipes<div dir="ltr" style="text-align: left;" trbidi="on">
<img class="img im-responsive center-block" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjOCRRyfmvhVh0yqOANCoL5iB5EJvyrk2mKzjEHt6eVNr7Qnm6Jk6F5BzFXzL8eg7sh_6RXs1auG4X43RZ-KkF3w7wjlfEopAkeYUrarpwxxNiWulFEYHdNp7tWx_pCjRE4Kpa2tR1vkYl5/s640/angular-pipes-builtin-async-custom.JPG" /><br />
<p> <strong>Important announcement</strong> : We are moving all our content to new website - <a href="https://witscad.com/courses"> Witscad Courses </a>. You can find the updated complete Angular course here - <a href="https://witscad.com/course/complete-angular-tutorial">A Complete Angular Tutorial</a>. Feel free to visit. </p>
In simple words, In Angular, a pipe takes in data as input and transforms it to a desired output. It is corresponding to what filters are in AngularJS.<br />
<h4 style="text-align: left;">
A quick example :</h4>
<div style="background: #f8f8f8; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: green; font-weight: bold;"><p></span>{{date | date:'shortDate'}}<span style="color: green; font-weight: bold;"></p></span> <span style="color: green; font-weight: bold;"><p></span>{{date | date:'longDate'}}<span style="color: green; font-weight: bold;"></p></span>
</pre>
</div>
<br />
It transforms a date string to short date and long date format.<br />
<br />
<h2 style="text-align: left;">
There are three type of Pipes Angular provides:</h2>
<h3 style="text-align: left;">
1) Builtin Pipes:</h3>
<div>
<br /></div>
There are several inbuilt pipes provided by Angular framework. Following is the list of some of the Builtin Pipes:<br />
<h4 style="text-align: left;">
</h4>
<h4 style="text-align: left;">
a) DatePipe:</h4>
<div style="background: #f8f8f8; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;">date_expression | date[:format]</pre>
</div>
<br />
where expression is a date object or a number and format indicates which date/time components to include. The format can be predifined as shown below or custom as shown in the table.<br />
<br />
<table class="table table-condensed active">
<tbody>
<tr>
<th>Format</th>
<th>Description</th>
</tr>
<tr>
<td>medium</td>
<td>equivalent to 'yMMMdjms' (e.g. Sep 3, 2010, 12:05:08 PM for en-US)</td>
</tr>
<tr>
<td>short</td>
<td>equivalent to 'yMdjm' (e.g. 9/3/2010, 12:05 PM for en-US)</td>
</tr>
<tr>
<td>fullDate</td>
<td>equivalent to 'yMMMMEEEEd' (e.g. Friday, September 3, 2010 for en-US)</td>
</tr>
<tr>
<td>longDate</td>
<td>equivalent to 'yMMMMd' (e.g. September 3, 2010 for en-US)</td>
</tr>
<tr>
<td>mediumDate</td>
<td>equivalent to 'yMMMd' (e.g. Sep 3, 2010 for en-US)</td>
</tr>
<tr>
<td>shortDate</td>
<td>equivalent to 'yMd' (e.g. 9/3/2010 for en-US)</td>
</tr>
<tr>
<td>mediumTime</td>
<td>equivalent to 'jms' (e.g. 12:05:08 PM for en-US)</td>
</tr>
<tr>
<td>shortTime</td>
<td>equivalent to 'jm' (e.g. 12:05 PM for en-US)</td>
</tr>
</tbody></table>
<br />
Example :<br />
<div style="background: #f8f8f8; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;">{{ dateObj | date }} // output is 'Jan 10, 2016'
{{ dateObj | date:'medium' }} // output is 'Jan 10, 2016, 2:10:15 PM'
{{ dateObj | date:'shortTime' }} // output is '2:10 PM'
{{ dateObj | date:'mmss' }} // output is '10:15'
</pre>
</div>
<br />
<br />
<h4 style="text-align: left;">
b) UpperCasePipe,</h4>
<div style="background: #f8f8f8; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;">expression | uppercase
</pre>
</div>
<br />
It converts value into an uppercase string using String.prototype.toUpperCase().<br />
<br />
Example:<br />
<div style="background: #f8f8f8; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: green; font-weight: bold;"><p></span>In uppercase: <span style="color: green; font-weight: bold;"><pre></span>'{{value | uppercase}}'<span style="color: green; font-weight: bold;"></pre></span>
</pre>
</div>
<br />
<h4 style="text-align: left;">
c) LowerCasePipe:</h4>
<div style="background: #f8f8f8; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;">expression | lowercase
</pre>
</div>
<br />
It converts value into a lowercase string using String.prototype.toLowerCase().<br />
<br />
Example:<br />
<div style="background: #f8f8f8; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: green; font-weight: bold;"><p></span>In lowercase: <span style="color: green; font-weight: bold;"><pre></span>'{{value | lowercase}}'<span style="color: green; font-weight: bold;"></pre></span>
</pre>
</div>
<br />
<h4 style="text-align: left;">
d) CurrencyPipe:</h4>
<div style="background: #f8f8f8; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;">number_expression | currency[:currencyCode[:symbolDisplay[:digitInfo]]]
</pre>
</div>
<br />
where<br />
<i>currencyCode</i> - the <a href="https://en.wikipedia.org/wiki/ISO_4217">ISO 4217</a> currency code, such as USD for the US dollar and EUR for the euro.<br />
<i><br /></i>
<i>symbolDisplay</i> - a boolean indicating whether to use the currency symbol or code. <br />
true - use symbol (e.g. $). <br />
false(default): use code (e.g. USD). <br />
<br />
<i>digitInfo -</i><br />
digitInfo is a string which has a following format: <br />
{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}<br />
<h4 style="text-align: left;">
</h4>
<h4 style="text-align: left;">
</h4>
<h4 style="text-align: left;">
e) PercentPipe:</h4>
<div style="background: #f8f8f8; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;">number_expression | percent[:digitInfo]
</pre>
</div>
where digitInfo is same as mentioned above.<br />
<br />
<i>Note </i>: Pipes can be chained as:{{ birthday | date | uppercase}}<br />
<br />
<br/>
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Post body ad responsive -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-4262325767595391" data-ad-format="auto" data-ad-slot="9970526860" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br/>
<h3 style="text-align: left;">
2. Async Pipes:</h3>
<div style="background: #f8f8f8; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;">observable_or_promise_expression | async
</pre>
</div>
<br />
An async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes.<br />
<br />
<h3 style="text-align: left;">
</h3>
<h3 style="text-align: left;">
3. Custom Pipes:</h3>
We can create very own custom pipes by using the @Pipe decorator and implementing the PipeTransform interface:<br />
<br />
Example:<br />
<!-- HTML generated using hilite.me --><br />
<div style="background: #f0f0f0; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #007020; font-weight: bold;">import</span> { Pipe, PipeTransform } from <span style="color: #4070a0;">'angular/core'</span>;
<span style="border: 1px solid #FF0000;">@</span>Pipe({ name<span style="color: #666666;">:</span> <span style="color: #4070a0;">'HtoS'</span> })
<span style="color: #007020; font-weight: bold;">export</span> <span style="color: #007020; font-weight: bold;">class</span> HoursToSeconds <span style="color: #007020; font-weight: bold;">implements</span> PipeTransform {
transform(value: <span style="color: #902000;">string</span>, args: <span style="color: #902000;">any</span>[]){
<span style="color: #007020; font-weight: bold;">return</span> <span style="color: #007020;">parseFloat</span>(value)<span style="color: #666666;">*</span><span style="color: #40a070;">3600</span>;
}
}
</pre>
</div>
<br />
<br />
<h2 style="text-align: left;">
Live Code:</h2>
<div>
Plunker here:
<a href="https://embed.plnkr.co/plunk/IJZ3E1d30wBqziOcdp6z?show=app,preview">https://embed.plnkr.co/plunk/IJZ3E1d30wBqziOcdp6z?show=app,preview</a>
</div>
</div>
Satya Jugranhttp://www.blogger.com/profile/02579918194785863102noreply@blogger.com0tag:blogger.com,1999:blog-4672721440989923845.post-12722772737141818442017-09-23T13:43:00.000-07:002019-01-10T05:37:49.715-08:00Angular 5 : Data and Event Bindings<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<img class="img img-responsive center-block" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiNO_cF4luVrRypfhO6GMu-mLNaB1FqR8i9e6uDXPiBm9ieiGuPx8jfuVcg0zR33YwWP1cOBUmvU_QvJbCqfhZudWj3xcLGkQ3Jfdnoxkgqb_qXRuYjOX85RbPtuIiQyQ-yWs9oFtJyNGJF/s640/angular-data-and-event-bindings.JPG" /></div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
<p> <strong>Important announcement</strong> : We are moving all our content to new website - <a href="https://witscad.com/courses"> Witscad Courses </a>. You can find the updated complete Angular course here - <a href="https://witscad.com/course/complete-angular-tutorial">A Complete Angular Tutorial</a>. Feel free to visit. </p>
<h2 style="text-align: left;">
<span id="goog_777891736"></span><span id="goog_777891737"></span></h2>
<h2 style="text-align: left;">
Angular provides many kinds of data binding</h2>
We can group all bindings into four categories by the direction in which data flows. Each category has its distinctive syntax:<br />
<h3 style="text-align: left;">
Interpolation</h3>
Any property in Component class can be shown as text through Interpolation written as {{}}<br />
<br />
<h3 style="text-align: left;">
Property Binding</h3>
It is similar to Interpolation but it is a preferable way of doing one way binding, especially in case of styles and attribute bindings. It has a syntax []<br />
<br />
<h3 style="text-align: left;">
Event Binding</h3>
It binds and event to a Component function. The events are standard browser events such as Click, DoubleClick etc.<br />
<br />
<h3 style="text-align: left;">
Two-way binding</h3>
It binds a Component property to an input element. The changes gets reflected in the property at the same time. This is actually a combination of One-way binding and Event-binding. It is written as Banana-in-a-box syntax [(..)]. The outer braces shows One-way binding and the inner brace shows Event binding.<br />
<br />
<br />
<h2 style="text-align: center;">
To Visualize</h2>
<div class="row">
<div class="col-xs-3 col-sm-3 col-md-3 col-lg-3" style="background: rgb(100,100,200); height: 350px;">
<h2>
DOM</h2>
</div>
<div class="col-xs-6 col-sm-6 col-md-6 col-lg-6">
<br />
<div class="text-center">
Interpolation : {{someText}}
</div>
<div style="border-right: 10px solid red; border-top: 10px solid transparent; height: 0; width: 0;">
</div>
<div style="border-top-style: solid;">
</div>
<div class="text-center" style="border-bottom: 10px solid transparent; border-right: 10px solid red; height: 0; width: 0;">
</div>
<div class="text-center" style="margin-top: 20px;">
Property Binding : <br />
<img [src]='prop.URL'>
</div>
<div>
<div style="border-right: 10px solid red; border-top: 10px solid transparent; height: 0; width: 0;">
</div>
<div style="border-top-style: solid;">
</div>
<div class="text-center" style="border-bottom: 10px solid transparent; border-right: 10px solid red; height: 0; width: 0;">
</div>
</div>
<div class="text-center" style="margin-top: 20px;">
Event Binding : <br />
<button (click)='showImage()'>
</div>
<div style="-moz-transform: rotate(180deg); -ms-transform: rotate(180deg); -o-transform: rotate(180deg); -webkit-transform: rotate(90deg); transform: rotate(180deg);">
<div style="border-right: 10px solid red; border-top: 10px solid transparent; height: 0; width: 0;">
</div>
<div style="border-top-style: solid;">
</div>
<div style="border-bottom: 10px solid transparent; border-right: 10px solid red; height: 0; width: 0;">
</div>
</div>
<div class="text-center" style="margin-top: 20px;">
Two way Binding : <br />
<input [(ngModel)]='Name'>
</div>
<div style="border-right: 10px solid red; border-top: 10px solid transparent; height: 0; width: 0;">
</div>
<div style="border-top-style: solid; margin-bottom: 5px;">
</div>
<div style="border-top-style: solid;">
</div>
<div style="-moz-transform: rotate(180deg); -ms-transform: rotate(180deg); -o-transform: rotate(180deg); -webkit-transform: rotate(90deg); transform: rotate(180deg);">
<div style="border-right: 10px solid red; border-top: 10px solid transparent; height: 0; width: 0;">
</div>
</div>
</div>
<div class="col-xs-3 col-sm-3 col-md-3 col-lg-3" style="background: rgb(200,100,100); height: 350px;">
<h2>
Component</h2>
</div>
</div>
<br />
<br />
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Post body ad responsive -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-4262325767595391" data-ad-format="auto" data-ad-slot="9970526860" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br />
<h3 style="text-align: left;">
Example</h3>
<div style="background: rgb(248, 248, 248); overflow: auto; padding: 0.2em 0.6em; text-align: left; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #204a87; font-weight: bold;"><input</span> <span style="color: #c4a000;">type=</span><span style="color: #4e9a06;">"text"</span> <span style="border: 1px solid #ef2929; color: #a40000;">[value]="myName"</span><span style="color: #204a87; font-weight: bold;">></span>
<span style="color: #204a87; font-weight: bold;"><button</span> <span style="border: 1px solid #ef2929; color: #a40000;">(click)="colorChange(textColor)"</span> <span style="border: 1px solid #ef2929; color: #a40000;">[style.color]="textColor"</span><span style="color: #204a87; font-weight: bold;">></span>Change My Color<span style="color: #204a87; font-weight: bold;"></button></span>
<span style="color: #204a87; font-weight: bold;"><input</span> <span style="color: #c4a000;">type=</span><span style="color: #4e9a06;">"text"</span> <span style="border: 1px solid #ef2929; color: #a40000;">[(ngModel)]="textColor"</span><span style="color: #204a87; font-weight: bold;">></span>
<span style="color: #204a87; font-weight: bold;"><table</span> <span style="color: #c4a000;">border=</span><span style="color: #4e9a06;">2</span><span style="color: #204a87; font-weight: bold;">></span>
<span style="color: #8f5902; font-style: italic;"><!-- expression calculates colspan=2 --></span>
<span style="color: #204a87; font-weight: bold;"><tr></span>
<span style="color: #204a87; font-weight: bold;"><td</span> <span style="border: 1px solid #ef2929; color: #a40000;">[attr.colspan]="1</span> <span style="border: 1px solid #ef2929; color: #a40000;">+</span> <span style="border: 1px solid #ef2929; color: #a40000;">1</span> <span style="border: 1px solid #ef2929; color: #a40000;">+</span> <span style="border: 1px solid #ef2929; color: #a40000;">1"</span><span style="color: #204a87; font-weight: bold;">></span>Left - Center - Right<span style="color: #204a87; font-weight: bold;"></td></span>
<span style="color: #204a87; font-weight: bold;"></tr></span>
<span style="color: #204a87; font-weight: bold;"><tr></span>
<span style="color: #204a87; font-weight: bold;"><td></span>1<span style="color: #204a87; font-weight: bold;"></td></span>
<span style="color: #204a87; font-weight: bold;"><td></span>2<span style="color: #204a87; font-weight: bold;"></td></span>
<span style="color: #204a87; font-weight: bold;"><td></span>3<span style="color: #204a87; font-weight: bold;"></td></span>
<span style="color: #204a87; font-weight: bold;"></tr></span>
<span style="color: #204a87; font-weight: bold;"></table></span>
</pre>
</div>
<h3 style="text-align: left;">
</h3>
<h3 style="text-align: left;">
Live Code </h3>
Plunker here:
<a href="https://embed.plnkr.co/plunk/BT8gj5?show=app,preview">https://embed.plnkr.co/plunk/BT8gj5?show=app,preview</a>
</div>
Satya Jugranhttp://www.blogger.com/profile/02579918194785863102noreply@blogger.com0tag:blogger.com,1999:blog-4672721440989923845.post-13807666146743165792017-06-13T12:07:00.000-07:002017-06-13T12:07:32.110-07:00Angular 2 - Services and Dependency Injection<div dir="ltr" style="text-align: left;" trbidi="on">
Let's look some definitions to understand the subject.<br />
<br />
A <span style="font-size: x-large;">Service </span>is a functionality that can be shared with different Components. Whenever we find some common aspects in our components, we usually separate it out as a Service.<br />
<br />
<span style="font-size: x-large;">Dependency Injection</span> is a coding pattern in which a class takes the instances of objects it needs which is called dependencies from an external source rather than creating them itself.<br />
<br />
In Angular 2, services are Singleton. It internally implements the Service Locator Pattern. This means each service register itself under one container as a single instance. Angular provides a built in Injector which acts as a container to hold the single instances of all registered services. Angular takes care of creation of Service instance and registering it to the Service container.<br />
<br />
<h2 style="text-align: left;">
The @Injectable() decorator</h2>
To inject the service into component, Angular 2 provides an Injector decorator : @Injectable().<br />
<br />
<h3 style="text-align: left;">
We broadly have the following steps to create a Service:</h3>
1) Create the service class<br />
2) Define the metadata with a decorator<br />
3) Import what we need.<br />
<br />
<br />
To understand the Service more, let's built a service in Angular 2 for getting the user profile details in the User component. Let's create some classes:<br />
<h4 style="text-align: left;">
1. IProfile interface</h4>
<div style="background: #f0f0f0; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #007020; font-weight: bold;">export</span> <span style="color: #007020; font-weight: bold;">interface</span> IProfile{
Name: <span style="color: #902000;">string</span>;
Age: <span style="color: #902000;">number</span>;
}
</pre>
</div>
<div>
<br />
<h4 style="text-align: left;">
2. Profile Class</h4>
</div>
<div style="background: #f0f0f0; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #007020; font-weight: bold;">import</span> {Component, Injectable} from <span style="color: #4070a0;">'@angular/core'</span>
<span style="color: #007020; font-weight: bold;">import</span> {IProfile} from <span style="color: #4070a0;">'./iprofile'</span>
@Component({
selector<span style="color: #666666;">:</span> <span style="color: #4070a0;">'profile'</span>,
template<span style="color: #666666;">:</span> `
<span style="color: #666666;"><</span>div<span style="color: #666666;">></span>
<span style="color: #666666;"><</span>h2<span style="color: #666666;">></span>Name <span style="color: #666666;">:</span> {{MyProfile.Name}}<span style="color: #666666;"><</span>/h2>
<span style="color: #666666;"><</span>h2<span style="color: #666666;">></span>Age <span style="color: #666666;">:</span> {{MyProfile.Age}}<span style="color: #666666;"><</span>/h2>
<span style="color: #666666;"><</span>/div>
`
})
<span style="color: #007020; font-weight: bold;">export</span> <span style="color: #007020; font-weight: bold;">class</span> Profile{
MyProfile : <span style="color: #902000;">IProfile</span>;
<span style="color: #007020; font-weight: bold;">constructor</span>(){
}
}
</pre>
</div>
<br />
<h4 style="text-align: left;">
3. ProfileService class</h4>
<div style="background: #f0f0f0; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #007020; font-weight: bold;">import</span> {Injectable} from <span style="color: #4070a0;">'@angular/core'</span>
<span style="color: #007020; font-weight: bold;">import</span> {IProfile} from <span style="color: #4070a0;">'./iprofile'</span>
@Injectable()
<span style="color: #007020; font-weight: bold;">export</span> <span style="color: #007020; font-weight: bold;">class</span> ProfileService{
getProfiles()<span style="color: #666666;">:</span> IProfile[]{
<span style="color: #007020; font-weight: bold;">return</span> [{
Name<span style="color: #666666;">:</span><span style="color: #4070a0;">'Bob'</span>,
Age: <span style="color: #902000;">25</span>
},
{
Name<span style="color: #666666;">:</span><span style="color: #4070a0;">'Alice'</span>,
Age: <span style="color: #902000;">23</span>
}];
}
}
</pre>
</div>
<br />
<h2 style="text-align: left;">
Registering a Service:</h2>
A Service can be registered in any component. However, it should be registered at root level component only. This is because it we register at two different nested level component, then the service will have two entire different instances in both components. However, we can register at any nested level component just in case if we require to use the service in that component or it's child components only.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjNBITR-vvIMvx7CbOCGCGMjOEYTrgr5-pquQUeoZE8abieFa6LyWX7pnURGxZd2iY5-hm4ZdeEX3x7kTU27nmTDi0iH2UO7HTPimLuHBq7m8IDvx_0PTPOZpHONXGOG63rKazx3Hj3TytI/s1600/DependencyInjection1.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="356" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjNBITR-vvIMvx7CbOCGCGMjOEYTrgr5-pquQUeoZE8abieFa6LyWX7pnURGxZd2iY5-hm4ZdeEX3x7kTU27nmTDi0iH2UO7HTPimLuHBq7m8IDvx_0PTPOZpHONXGOG63rKazx3Hj3TytI/s640/DependencyInjection1.png" width="640" /></a></div>
<br />
In above figure, <br />
1. The "Service 1" is registered at app level, so it is available to all the nested components.<br />
2. The "Service 2" is registered at "Parent 1" component, so it is available to Parent 1, Child1, Child2 and Child 3 components.<br />
3. The "Service 3" is registered at "Child 1" component, so it is available to "Child 1" only, as no other component comes under its hierarchy.<br />
4. The "Service 4" is registered at "Parent 2" component, so it is available to Parent 2 and Child 4 only.<br />
<br />
Now, if we try to register "Service 1" both in root component and "Parent 1" component, then it's two instances will be created. That is why, we should register the service at an appropriate component level as per it's usage.<br />
<br />
Continuing with our example, Import ProfileService and change the @NgModule() decorator of root level component as:<br />
<br />
<div style="background: #f0f0f0; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #007020; font-weight: bold;">import</span> {ProfileService} from <span style="color: #4070a0;">'./profile.service'</span>;
.
.
.
@NgModule({
imports<span style="color: #666666;">:</span> [ BrowserModule ],
declarations<span style="color: #666666;">:</span> [ App ],
providers<span style="color: #666666;">:</span>[ProfileService],
bootstrap<span style="color: #666666;">:</span> [ App ]
})
</pre>
</div>
<br />
<br />
<h2 style="text-align: left;">
Injecting a Service in component:</h2>
<div>
We can inject our service as a parameter to our constructor class.<br />
<br /></div>
<div style="background: #f0f0f0; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #007020; font-weight: bold;">constructor</span>(<span style="color: #007020; font-weight: bold;">private</span> _profileService: <span style="color: #902000;">ProfileService</span>){
}
</pre>
</div>
<br />
Now, we can execute the methods of our service to get the data. We can call the service method inside our constructor, but what if the service wants to pull to data from backend. We don't want the construction of our class halted till the time we pull the data.<br />
A better solution would be to implement the <i>OnInit </i>interface hook provided by Angular 2 and call the service method inside <i>ngOnInit</i>() function. (Know more about Angular hooks here.)<br />
<br />
Modify the Profile class as below:<br />
<br />
<div style="background: #f0f0f0; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #007020; font-weight: bold;">import</span> {Component, Injectable} from <span style="color: #4070a0;">'@angular/core'</span>
<span style="color: #007020; font-weight: bold;">import</span> {ProfileService} from <span style="color: #4070a0;">'./profile.service'</span>;
<span style="color: #007020; font-weight: bold;">import</span> {IProfile} from <span style="color: #4070a0;">'./iprofile'</span>
@Component({
selector<span style="color: #666666;">:</span> <span style="color: #4070a0;">'profile'</span>,
template<span style="color: #666666;">:</span> `
<span style="color: #666666;"><</span>div<span style="color: #666666;">></span>
<span style="color: #666666;"><</span>h2<span style="color: #666666;">></span>Name <span style="color: #666666;">:</span> {{MyProfile.Name}}<span style="color: #666666;"><</span>/h2>
<span style="color: #666666;"><</span>h4<span style="color: #666666;">></span>Age <span style="color: #666666;">:</span> {{MyProfile.Age}}<span style="color: #666666;"><</span>/h4>
<span style="color: #666666;"><</span>/div>
`,
})
<span style="color: #007020; font-weight: bold;">export</span> <span style="color: #007020; font-weight: bold;">class</span> Profile <span style="color: #007020; font-weight: bold;">implements</span> OnInit{
ProfileList : <span style="color: #902000;">IProfile</span>[];
MyProfile : <span style="color: #902000;">IProfile</span>;
<span style="color: #007020; font-weight: bold;">constructor</span>(<span style="color: #007020; font-weight: bold;">private</span> _profileService: <span style="color: #902000;">ProfileService</span>){
}
ngOnInit(){
<span style="color: #007020; font-weight: bold;">this</span>.ProfileList <span style="color: #666666;">=</span> <span style="color: #007020; font-weight: bold;">this</span>._profileService.getProfiles();
<span style="color: #007020; font-weight: bold;">this</span>.MyProfile <span style="color: #666666;">=</span> <span style="color: #007020; font-weight: bold;">this</span>.ProfileList[<span style="color: #40a070;">0</span>];
}
}
</pre>
</div>
<br />
<h2 style="text-align: left;">
To summarize:</h2>
* Create a Service class<br />
* Use @Injectable() decorator to the service.<br />
* Register the service at the root component.<br />
* Inject the service as a constructor parameter of the dependent class.<br />
<br />
<h2 style="text-align: left;">
Live Code:</h2>
Plunker here:
<a href="https://embed.plnkr.co/SbgOOoUtJIeaQBY2FizW?show=app,preview">https://embed.plnkr.co/SbgOOoUtJIeaQBY2FizW?show=app,preview</a>
</div>
Witspry Technovatehttp://www.blogger.com/profile/13599435720165810309noreply@blogger.com0tag:blogger.com,1999:blog-4672721440989923845.post-29151847586308814402017-06-13T12:04:00.000-07:002017-06-13T12:04:10.012-07:00Angular 2 - Working with Nested Components<div dir="ltr" style="text-align: left;" trbidi="on">
<h2 style="text-align: left;">
What are Nested/Child components?</h2>
<div>
<div>
A Component in Angular 2 can have child components. Also, those child components can have their own further child components. Angular 2 seamlessly supports nested components.</div>
<div>
<br /></div>
<div>
As an example, consider a calculator as a top level component. It is built with several other child components like screen component, button component, body component, battery component etc. These screen, button, body and battery components are nested components of Calculator component.</div>
<div>
<br /></div>
<div>
The nested component have all the functionalities just as any other Angular 2 component.</div>
<div>
<h4 style="text-align: left;">
Now several question arises in our mind:</h4>
</div>
<div class="row">
<div class="col-xs-2 col-sm-3 col-md-3 col-lg-3">
<img class="img-responsive center-block" src="https://witspry.in/ContentServer/Images/person_thinking.jpg" />
</div>
<div class="col-xs-10 col-sm-9 col-md-9 col-lg-9">
<br />
<ol>
<li>How we are going to use our nested components in its parent component?</li>
<li>How we can pass data from parent component into its child component?</li>
<li>How can we get the data back from child component to parent component?</li>
<li>How does the child component can respond to the parent events?</li>
<li>How does the parent component can respond to the child events?</li>
</ol>
</div>
</div>
<br />
<div>
To answer all these questions, lets us built a step-by-step example where we have a profile page of a person. It will also have a friend's list.</div>
<div>
<br /></div>
<h2 style="text-align: left;">
1) Building Parent and Child components.</h2>
<div>
Let's first built our Child component in our example app which is Friend list component.<br />
<br /></div>
<div style="background: #f0f0f0; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #007020; font-weight: bold;">import</span> { Component } from <span style="color: #4070a0;">'@angular/core'</span>;
@Component({
selector<span style="color: #666666;">:</span> <span style="color: #4070a0;">'my-friends'</span>,
template<span style="color: #666666;">:</span> `<span style="color: #666666;"><</span>div<span style="color: #666666;">></span>
<span style="color: #666666;"><</span>table<span style="color: #666666;">></span>
<span style="color: #666666;"><</span>tr <span style="color: #666666;">*</span>ngFor<span style="color: #666666;">=</span><span style="color: #4070a0;">'let friend of friends'</span><span style="color: #666666;">></span>
<span style="color: #666666;"><</span>td<span style="color: #666666;">></span>{{friend}}<span style="color: #666666;"><</span>/td>
<td<span style="color: #666666;">></span>
<span style="color: #666666;"><</span>img
src<span style="color: #666666;">=</span><span style="color: #4070a0;">"http://witspry.in/ContentServer/Images/User/user.png"</span>
width<span style="color: #666666;">=</span><span style="color: #4070a0;">"20"</span> <span style="color: #666666;">/></span>
<span style="color: #666666;"><</span>/td>
<span style="color: #666666;"><</span>/tr>
<span style="color: #666666;"><</span>/table>
<span style="color: #666666;"><</span>/div>`
})
<span style="color: #007020; font-weight: bold;">export</span> <span style="color: #007020; font-weight: bold;">class</span> MyFriendsComponent{
friends: <span style="color: #902000;">Array</span><span style="color: #666666;"><</span><span style="color: #902000;">string</span><span style="color: #666666;">></span> <span style="color: #666666;">=</span> [
<span style="color: #4070a0;">'Friend 1'</span>,
<span style="color: #4070a0;">'Friend 2'</span>,
<span style="color: #4070a0;">'Friend 3'</span>,
<span style="color: #4070a0;">'Friend 4'</span>,
<span style="color: #4070a0;">'Friend 5'</span>,
];
}
</pre>
</div>
<br />
Now, let's built our Parent component which is User's profile page.<br />
<br />
<div style="background: #f0f0f0; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #007020; font-weight: bold;">import</span> { Component } from <span style="color: #4070a0;">'@angular/core'</span>;
<span style="color: #007020; font-weight: bold;">import</span> {MyFriendsComponent} from <span style="color: #4070a0;">'./myFriends'</span>;
@Component({
selector<span style="color: #666666;">:</span> <span style="color: #4070a0;">'my-profile'</span>,
template<span style="color: #666666;">:</span>`<span style="color: #666666;"><</span>img [src]<span style="color: #666666;">=</span><span style="color: #4070a0;">"imgURL"</span> width<span style="color: #666666;">=</span><span style="color: #4070a0;">"50"</span><span style="color: #666666;">/></span>
<span style="color: #666666;"><</span>h3<span style="color: #666666;">></span>My Friends<span style="color: #666666;"><</span>/h3>
<span style="color: #666666;"><</span>my<span style="color: #666666;">-</span>friends<span style="color: #666666;">><</span>/my-friends>`
})
<span style="color: #007020; font-weight: bold;">export</span> <span style="color: #007020; font-weight: bold;">class</span> MyProfileComponent{
<span style="color: #007020; font-weight: bold;">constructor</span>(){
<span style="color: #007020; font-weight: bold;">this</span>.imgURL <span style="color: #666666;">=</span> <span style="color: #4070a0;">'http://witspry.in/ContentServer/Images/User/user_circle.png'</span>;
}
}
</pre>
</div>
<br />
* See the above example as how the <my-friends> is used as a directive to the Profile component.<br />
<br />
Now, in main app import both component and add them in the "declarations" array.<br />
<br />
<div style="background: #f0f0f0; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;">@NgModule({
imports<span style="color: #666666;">:</span> [ BrowserModule ],
declarations<span style="color: #666666;">:</span> [ App, MyProfileComponent, MyFriendsComponent ],
bootstrap<span style="color: #666666;">:</span> [ App ]
})
<span style="color: #007020; font-weight: bold;">export</span> <span style="color: #007020; font-weight: bold;">class</span> AppModule {}
</pre>
</div>
<br />
<br />
Next, we are going to see how parent component provides input to child component and how child component emit events to send the payloads to parent component. Here is a diagram to get a gist of it.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh3ryZSHs2rau8M8LA1H5POAfgBJ7Zos935LYlpB8kp28yrZxx9D6vq76vEBN9eB2YeAj5r9coec-2iMFsCI0w1nj04SZptDk5PWjYv3C4vvy6uzS2KkFT-B8SV4xFsUHu7cmP59JuNa_jT/s1600/NestedComponentsOverview.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="480" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh3ryZSHs2rau8M8LA1H5POAfgBJ7Zos935LYlpB8kp28yrZxx9D6vq76vEBN9eB2YeAj5r9coec-2iMFsCI0w1nj04SZptDk5PWjYv3C4vvy6uzS2KkFT-B8SV4xFsUHu7cmP59JuNa_jT/s640/NestedComponentsOverview.png" width="640" /></a></div>
<br />
<br />
<h2 style="text-align: left;">
2) Passing data using @Input() decorator.</h2>
@Input() decorator to the rescue<br />
<br />
Add a variable name as a following line with @Input() decorator.<br />
<br />
<div style="background: #f0f0f0; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #007020; font-weight: bold;">export</span> <span style="color: #007020; font-weight: bold;">class</span> MyFriendComponent{
@Input() name : <span style="color: #902000;">string</span>;
}
</pre>
</div>
<br />
Change our User's profile page as:<br />
<br />
<div style="background: #f0f0f0; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;">@Component({
selector<span style="color: #666666;">:</span> <span style="color: #4070a0;">'my-profile'</span>,
template<span style="color: #666666;">:</span>`
<span style="color: #666666;"><</span>img [src]<span style="color: #666666;">=</span><span style="color: #4070a0;">"imgURL"</span> width<span style="color: #666666;">=</span><span style="color: #4070a0;">"50"</span><span style="color: #666666;">/></span>
<span style="color: #666666;"><</span>h3<span style="color: #666666;">></span>My Friends<span style="color: #666666;"><</span>/h3>
<span style="color: #666666;"><</span>div <span style="color: #666666;">*</span>ngFor<span style="color: #666666;">=</span><span style="color: #4070a0;">"let friend of friends"</span><span style="color: #666666;">></span>
<span style="color: #666666;"><</span>my<span style="color: #666666;">-</span>friend [name]<span style="color: #666666;">=</span><span style="color: #4070a0;">'friend'</span><span style="color: #666666;">></my-friend></span>
<span style="color: #666666;"><</span>/div>
`
})
<span style="color: #007020; font-weight: bold;">export</span> <span style="color: #007020; font-weight: bold;">class</span> MyProfileComponent{
<span style="color: #007020; font-weight: bold;">constructor</span>(){
<span style="color: #007020; font-weight: bold;">this</span>.imgURL <span style="color: #666666;">=</span> <span style="color: #4070a0;">'http://witspry.in/ContentServer/Images/User/user_circle.png'</span>;
<span style="color: #007020; font-weight: bold;">this</span>.friends <span style="color: #666666;">=</span> [
<span style="color: #4070a0;">'Friend 1'</span>,
<span style="color: #4070a0;">'Friend 2'</span>,
<span style="color: #4070a0;">'Friend 3'</span>,
<span style="color: #4070a0;">'Friend 4'</span>,
<span style="color: #4070a0;">'Friend 5'</span>
];
}
}
</pre>
</div>
<br />
See the line - <i><my-friend [name]='friend'></my-friend></i><br />
Here we are passing a friend name to the "name" property of the child component.<br />
<br />
<h2 style="text-align: left;">
3) Raising an event using @Output() decorator</h2>
<div>
<div>
The @Output directive enables a child component to use its properties in the parent component.</div>
<div>
<br /></div>
<div>
Lets modify our MyFriend component as:</div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<div style="background: #f0f0f0; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #007020; font-weight: bold;">import</span> { Component, Input, Output, EventEmitter } from <span style="color: #4070a0;">'@angular/core'</span>;
@Component({
selector<span style="color: #666666;">:</span> <span style="color: #4070a0;">'my-friend'</span>,
template<span style="color: #666666;">:</span> `<span style="color: #666666;"><</span>div<span style="color: #666666;">></span>
<span style="color: #666666;"><</span>table<span style="color: #666666;">></span>
<span style="color: #666666;"><</span>tr<span style="color: #666666;">></span>
<span style="color: #666666;"><</span>td<span style="color: #666666;">></span>{{name}}<span style="color: #666666;"><</span>/td>
<span style="color: #666666;"><</span>td<span style="color: #666666;">></span>
<span style="color: #666666;"><</span>img src<span style="color: #666666;">=</span><span style="color: #4070a0;">"http://putiw.xyz/clashroyaleunlimitedgems/img/user.png"</span>
width<span style="color: #666666;">=</span><span style="color: #4070a0;">"20"</span> <span style="color: #666666;">/></span>
<span style="color: #666666;"> <</span>/td>
<span style="color: #666666;"><</span>td<span style="color: #666666;">><</span>button (click)<span style="color: #666666;">=</span><span style="color: #4070a0;">'OnClick()'</span><span style="color: #666666;">></span>Ping<span style="color: #666666;"><</span>/button></td>
<span style="color: #666666;"><</span>td<span style="color: #666666;">></span> {{timesPinged}} <span style="color: #666666;"><</span>/td>
<span style="color: #666666;"><</span>/tr>
<span style="color: #666666;"><</span>/table>
<span style="color: #666666;"><</span>/div>`
})
<span style="color: #007020; font-weight: bold;">export</span> <span style="color: #007020; font-weight: bold;">class</span> MyFriendComponent{
@Input() name : <span style="color: #902000;">string</span>;
timesPinged: <span style="color: #902000;">number</span> <span style="color: #666666;">=</span> <span style="color: #40a070;">0</span>;
@Output() pingClicked: <span style="color: #902000;">EventEmitter</span><span style="color: #666666;"><</span><span style="color: #902000;">string</span><span style="color: #666666;">></span> <span style="color: #666666;">=</span> <span style="color: #007020; font-weight: bold;">new</span> EventEmitter<span style="color: #666666;"><</span><span style="color: #902000;">string</span><span style="color: #666666;">></span>();
OnClick(){
<span style="color: #007020; font-weight: bold;">this</span>.timesPinged<span style="color: #666666;">++</span>;
<span style="color: #007020; font-weight: bold;">this</span>.pingClicked.emit(<span style="color: #4070a0;">'You pinged '</span> <span style="color: #666666;">+</span> <span style="color: #007020; font-weight: bold;">this</span>.name <span style="color: #666666;">+</span> <span style="color: #4070a0;">' '</span> <span style="color: #666666;">+</span>
<span style="color: #007020; font-weight: bold;"> this</span>.timesPinged <span style="color: #666666;">+</span> (<span style="color: #007020; font-weight: bold;">this</span>.timesPinged <span style="color: #666666;">==</span> <span style="color: #40a070;">1</span><span style="color: #666666;">?</span> <span style="color: #4070a0;">' time'</span> <span style="color: #666666;">:</span> <span style="color: #4070a0;">' times'</span>));
}
}
</pre>
</div>
<br />
Here, we have imported <i>Output </i>and <i>EventEmitter </i>from Angular core library. Also, we have defined an event using <i>@Output()</i> decorator. The <i>OnClick </i>is a local function which is invoked from button's click event. Since the "<i>pingClicked</i>" is decorated with @<i>Output()</i>, it's emit function is able to notify the parent component.<br />
<br />
Now, change the parent component to capture the raised event from it's child component as below:<br />
<br />
<div style="background: #f0f0f0; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #007020; font-weight: bold;">import</span> { Component } from <span style="color: #4070a0;">'@angular/core'</span>;
@Component({
selector<span style="color: #666666;">:</span> <span style="color: #4070a0;">'my-profile'</span>,
template<span style="color: #666666;">:</span> `
<span style="color: #666666;"><</span>img [src]<span style="color: #666666;">=</span><span style="color: #4070a0;">"imgURL"</span> width<span style="color: #666666;">=</span><span style="color: #4070a0;">"50"</span><span style="color: #666666;">/></span>
<span style="color: #666666;"><</span>br <span style="color: #666666;">/></span>
{{pingMessage}}
<span style="color: #666666;"><</span>br <span style="color: #666666;">/></span>
Total Pings today <span style="color: #666666;">:</span> {{totalPings}}
<span style="color: #666666;"><</span>h3<span style="color: #666666;">></span>My Friends<span style="color: #666666;"><</span>/h3>
<span style="color: #666666;"><</span>div <span style="color: #666666;">*</span>ngFor<span style="color: #666666;">=</span><span style="color: #4070a0;">"let friend of friends"</span><span style="color: #666666;">></span>
<span style="color: #666666;"><</span>my<span style="color: #666666;">-</span>friend [name]<span style="color: #666666;">=</span><span style="color: #4070a0;">'friend'</span>
(pingClicked)<span style="color: #666666;">=</span><span style="color: #4070a0;">'onFriendPingClicked($event)'</span><span style="color: #666666;">></span>
<span style="color: #666666;"><</span>/my-friend>
<span style="color: #666666;"><</span>/div>
`
})
<span style="color: #007020; font-weight: bold;">export</span> <span style="color: #007020; font-weight: bold;">class</span> MyProfileComponent{
<span style="color: #007020; font-weight: bold;">constructor</span>(){
<span style="color: #007020; font-weight: bold;">this</span>.imgURL <span style="color: #666666;">=</span>
<span style="color: #4070a0;">'http://witspry.in/ContentServer/Images/User/user_circle.png'</span>;
<span style="color: #007020; font-weight: bold;">this</span>.friends <span style="color: #666666;">=</span> [
<span style="color: #4070a0;">'Friend A'</span>,
<span style="color: #4070a0;">'Friend B'</span>,
<span style="color: #4070a0;">'Friend C'</span>,
<span style="color: #4070a0;">'Friend D'</span>,
<span style="color: #4070a0;">'Friend E'</span>
];
<span style="color: #007020; font-weight: bold;">this</span>.totalPings <span style="color: #666666;">=</span> <span style="color: #40a070;">0</span>;
<span style="color: #007020; font-weight: bold;">this</span>.pingMessage <span style="color: #666666;">=</span> <span style="color: #4070a0;">''</span>;
}
onFriendPingClicked(pingMessage: <span style="color: #902000;">string</span>)<span style="color: #666666;">:</span> <span style="color: #007020; font-weight: bold;">void</span>{
<span style="color: #007020; font-weight: bold;">this</span>.totalPings<span style="color: #666666;">++</span>;
<span style="color: #007020; font-weight: bold;">this</span>.pingMessage <span style="color: #666666;">=</span> pingMessage;
}
}
</pre>
</div>
<br />
<span style="font-size: large;">Finally</span>, we have added an Event binding (please check our previous article in Angular 2 : Event bindings) which is "pingClicked". Have you remember, this was decorated with @Output in our child component. Yes, this is how was are able to use it here. Also, it is assigned to a function "onFriendPingClicked($event)". The $event contains the data that the child component emits on the occurrence of it's event.<br />
<br />
<h3 style="text-align: left;">
To Summarize:</h3>
* Use @Input() decorator to pass data to child component.<br />
* Use @Output() decorator to raise an event to parent component. Note : The @Output() decorator property can be only of EventEmitter type.<br />
<br />
<h2 style="text-align: left;">
Live Code</h2>
<div>
Plunker here:
<a href="https://embed.plnkr.co/nmtTHLz0vNu0HTaywwCB?amp;show=app,preview">https://embed.plnkr.co/nmtTHLz0vNu0HTaywwCB?amp;show=app,preview</a>
</div>
</div>
</div>
Witspry Technovatehttp://www.blogger.com/profile/13599435720165810309noreply@blogger.com0tag:blogger.com,1999:blog-4672721440989923845.post-42878102316203306352017-06-13T11:53:00.000-07:002017-06-13T11:53:10.441-07:00Angular 2 Pipes<div dir="ltr" style="text-align: left;" trbidi="on">
In simple words, In Angular 2, a pipe takes in data as input and transforms it to a desired output. It is corresponding to what filters are in Angular 1.<br />
<h4 style="text-align: left;">
A quick example :</h4>
<div style="background: #f8f8f8; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: green; font-weight: bold;"><p></span>{{date | date:'shortDate'}}<span style="color: green; font-weight: bold;"></p></span> <span style="color: green; font-weight: bold;"><p></span>{{date | date:'longDate'}}<span style="color: green; font-weight: bold;"></p></span>
</pre>
</div>
<br />
It transforms a date string to short date and long date format.<br />
<br />
<h2 style="text-align: left;">
There are three type of Pipes Angular 2 provides:</h2>
<h3 style="text-align: left;">
1) Builtin Pipes:</h3>
<div>
<br /></div>
There are several inbuilt pipes provided by Angular 2 framework. Following is the list of some of the Builtin Pipes:<br />
<h4 style="text-align: left;">
</h4>
<h4 style="text-align: left;">
a) DatePipe:</h4>
<div style="background: #f8f8f8; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;">date_expression | date[:format]</pre>
</div>
<br />
where expression is a date object or a number and format indicates which date/time components to include. The format can be predifined as shown below or custom as shown in the table.<br />
<br />
<table class="table table-condensed active">
<tbody>
<tr>
<th>Format</th>
<th>Description</th>
</tr>
<tr>
<td>medium</td>
<td>equivalent to 'yMMMdjms' (e.g. Sep 3, 2010, 12:05:08 PM for en-US)</td>
</tr>
<tr>
<td>short</td>
<td>equivalent to 'yMdjm' (e.g. 9/3/2010, 12:05 PM for en-US)</td>
</tr>
<tr>
<td>fullDate</td>
<td>equivalent to 'yMMMMEEEEd' (e.g. Friday, September 3, 2010 for en-US)</td>
</tr>
<tr>
<td>longDate</td>
<td>equivalent to 'yMMMMd' (e.g. September 3, 2010 for en-US)</td>
</tr>
<tr>
<td>mediumDate</td>
<td>equivalent to 'yMMMd' (e.g. Sep 3, 2010 for en-US)</td>
</tr>
<tr>
<td>shortDate</td>
<td>equivalent to 'yMd' (e.g. 9/3/2010 for en-US)</td>
</tr>
<tr>
<td>mediumTime</td>
<td>equivalent to 'jms' (e.g. 12:05:08 PM for en-US)</td>
</tr>
<tr>
<td>shortTime</td>
<td>equivalent to 'jm' (e.g. 12:05 PM for en-US)</td>
</tr>
</tbody></table>
<br />
Example :<br />
<div style="background: #f8f8f8; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;">{{ dateObj | date }} // output is 'Jan 10, 2016'
{{ dateObj | date:'medium' }} // output is 'Jan 10, 2016, 2:10:15 PM'
{{ dateObj | date:'shortTime' }} // output is '2:10 PM'
{{ dateObj | date:'mmss' }} // output is '10:15'
</pre>
</div>
<br />
<br />
<h4 style="text-align: left;">
b) UpperCasePipe,</h4>
<div style="background: #f8f8f8; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;">expression | uppercase
</pre>
</div>
<br />
It converts value into an uppercase string using String.prototype.toUpperCase().<br />
<br />
Example:<br />
<div style="background: #f8f8f8; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: green; font-weight: bold;"><p></span>In uppercase: <span style="color: green; font-weight: bold;"><pre></span>'{{value | uppercase}}'<span style="color: green; font-weight: bold;"></pre></span>
</pre>
</div>
<br />
<h4 style="text-align: left;">
c) LowerCasePipe:</h4>
<div style="background: #f8f8f8; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;">expression | lowercase
</pre>
</div>
<br />
It converts value into a lowercase string using String.prototype.toLowerCase().<br />
<br />
Example:<br />
<div style="background: #f8f8f8; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: green; font-weight: bold;"><p></span>In lowercase: <span style="color: green; font-weight: bold;"><pre></span>'{{value | lowercase}}'<span style="color: green; font-weight: bold;"></pre></span>
</pre>
</div>
<br />
<h4 style="text-align: left;">
d) CurrencyPipe:</h4>
<div style="background: #f8f8f8; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;">number_expression | currency[:currencyCode[:symbolDisplay[:digitInfo]]]
</pre>
</div>
<br />
where<br />
<i>currencyCode</i> - the <a href="https://en.wikipedia.org/wiki/ISO_4217">ISO 4217</a> currency code, such as USD for the US dollar and EUR for the euro.<br />
<i><br /></i>
<i>symbolDisplay</i> - a boolean indicating whether to use the currency symbol or code. <br />
true - use symbol (e.g. $). <br />
false(default): use code (e.g. USD). <br />
<br />
<i>digitInfo -</i><br />
digitInfo is a string which has a following format: <br />
{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}<br />
<h4 style="text-align: left;">
</h4>
<h4 style="text-align: left;">
</h4>
<h4 style="text-align: left;">
e) PercentPipe:</h4>
<div style="background: #f8f8f8; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;">number_expression | percent[:digitInfo]
</pre>
</div>
where digitInfo is same as mentioned above.<br />
<br />
<i>Note </i>: Pipes can be chained as:{{ birthday | date | uppercase}}<br />
<br />
<h3 style="text-align: left;">
</h3>
<h3 style="text-align: left;">
2. Async Pipes:</h3>
<div style="background: #f8f8f8; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;">observable_or_promise_expression | async
</pre>
</div>
<br />
An async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes.<br />
<br />
<h3 style="text-align: left;">
</h3>
<h3 style="text-align: left;">
3. Custom Pipes:</h3>
We can create very own custom pipes by using the @Pipe decorator and implementing the PipeTransform interface:<br />
<br />
Example:<br />
<!-- HTML generated using hilite.me --><br />
<div style="background: #f0f0f0; overflow: auto; padding: 0.2em 0.6em; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #007020; font-weight: bold;">import</span> { Pipe, PipeTransform } from <span style="color: #4070a0;">'angular2/core'</span>;
<span style="border: 1px solid #FF0000;">@</span>Pipe({ name<span style="color: #666666;">:</span> <span style="color: #4070a0;">'HtoS'</span> })
<span style="color: #007020; font-weight: bold;">export</span> <span style="color: #007020; font-weight: bold;">class</span> HoursToSeconds <span style="color: #007020; font-weight: bold;">implements</span> PipeTransform {
transform(value: <span style="color: #902000;">string</span>, args: <span style="color: #902000;">any</span>[]){
<span style="color: #007020; font-weight: bold;">return</span> <span style="color: #007020;">parseFloat</span>(value)<span style="color: #666666;">*</span><span style="color: #40a070;">3600</span>;
}
}
</pre>
</div>
<br />
<br />
<h2 style="text-align: left;">
Live Code:</h2>
<div>
Plunker here:
<a href="https://embed.plnkr.co/plunk/IJZ3E1d30wBqziOcdp6z?show=app,preview">https://embed.plnkr.co/plunk/IJZ3E1d30wBqziOcdp6z?show=app,preview</a>
</div>
</div>
Witspry Technovatehttp://www.blogger.com/profile/13599435720165810309noreply@blogger.com0tag:blogger.com,1999:blog-4672721440989923845.post-27654067847939078902017-06-13T11:36:00.000-07:002017-06-13T11:36:27.311-07:00Angular 2 - Data Bindings<div dir="ltr" style="text-align: left;" trbidi="on">
<h2 style="text-align: left;">
Angular provides many kinds of data binding</h2>
We can group all bindings into three categories by the direction in which data flows. Each category has its distinctive syntax:<br />
<h3 style="text-align: left;">
Interpolation</h3>
Any property in Component class can be shown as text through Interpolation written as {{}}<br />
<br />
<h3 style="text-align: left;">
Property Binding</h3>
It is similar to Interpolation but it is a preferable way of doing one way binding, especially in case of styles and attribute bindings. It has a syntax []<br />
<br />
<h3 style="text-align: left;">
Event Binding</h3>
It binds and event to a Component function. The events are standard browser events such as Click, DoubleClick etc.<br />
<br />
<h3 style="text-align: left;">
Two-way binding</h3>
It binds a Component property to an input element. The changes gets reflected in the property at the same time. This is actually a combination of One-way binding and Event-binding. It is written as Banana-in-a-box syntax [(..)]. The outer braces shows One-way binding and the inner brace shows Event binding.<br />
<br />
<br />
<h2 style="text-align: center;">
To Visualize</h2>
<div class="row">
<div class="col-xs-3 col-sm-3 col-md-3 col-lg-3" style="background: rgb(100,100,200); height: 350px;">
<h2>
DOM</h2>
</div>
<div class="col-xs-6 col-sm-6 col-md-6 col-lg-6">
<br />
<div class="text-center">
Interpolation : {{someText}}
</div>
<div style="border-right: 10px solid red; border-top: 10px solid transparent; height: 0; width: 0;">
</div>
<div style="border-top-style: solid;">
</div>
<div class="text-center" style="border-bottom: 10px solid transparent; border-right: 10px solid red; height: 0; width: 0;">
</div>
<div class="text-center" style="margin-top: 20px;">
Property Binding : <br />
<img [src]='prop.URL'>
</div>
<div>
<div style="border-right: 10px solid red; border-top: 10px solid transparent; height: 0; width: 0;">
</div>
<div style="border-top-style: solid;">
</div>
<div class="text-center" style="border-bottom: 10px solid transparent; border-right: 10px solid red; height: 0; width: 0;">
</div>
</div>
<div class="text-center" style="margin-top: 20px;">
Event Binding : <br />
<button (click)='showImage()'>
</div>
<div style="-moz-transform: rotate(180deg); -ms-transform: rotate(180deg); -o-transform: rotate(180deg); -webkit-transform: rotate(90deg); transform: rotate(180deg);">
<div style="border-right: 10px solid red; border-top: 10px solid transparent; height: 0; width: 0;">
</div>
<div style="border-top-style: solid;">
</div>
<div style="border-bottom: 10px solid transparent; border-right: 10px solid red; height: 0; width: 0;">
</div>
</div>
<div class="text-center" style="margin-top: 20px;">
Two way Binding : <br />
<input [(ngModel)]='Name'>
</div>
<div style="border-right: 10px solid red; border-top: 10px solid transparent; height: 0; width: 0;">
</div>
<div style="border-top-style: solid; margin-bottom: 5px;">
</div>
<div style="border-top-style: solid;">
</div>
<div style="-moz-transform: rotate(180deg); -ms-transform: rotate(180deg); -o-transform: rotate(180deg); -webkit-transform: rotate(90deg); transform: rotate(180deg);">
<div style="border-right: 10px solid red; border-top: 10px solid transparent; height: 0; width: 0;">
</div>
</div>
</div>
<div class="col-xs-3 col-sm-3 col-md-3 col-lg-3" style="background: rgb(200,100,100); height: 350px;">
<h2>
Component</h2>
</div>
</div>
<br />
<h3 style="text-align: left;">
Example</h3>
<div style="background: rgb(248, 248, 248); overflow: auto; padding: 0.2em 0.6em; text-align: left; width: auto;">
<pre style="line-height: 125%; margin: 0;"><span style="color: #204a87; font-weight: bold;"><input</span> <span style="color: #c4a000;">type=</span><span style="color: #4e9a06;">"text"</span> <span style="border: 1px solid #ef2929; color: #a40000;">[value]="myName"</span><span style="color: #204a87; font-weight: bold;">></span>
<span style="color: #204a87; font-weight: bold;"><button</span> <span style="border: 1px solid #ef2929; color: #a40000;">(click)="colorChange(textColor)"</span> <span style="border: 1px solid #ef2929; color: #a40000;">[style.color]="textColor"</span><span style="color: #204a87; font-weight: bold;">></span>Change My Color<span style="color: #204a87; font-weight: bold;"></button></span>
<span style="color: #204a87; font-weight: bold;"><input</span> <span style="color: #c4a000;">type=</span><span style="color: #4e9a06;">"text"</span> <span style="border: 1px solid #ef2929; color: #a40000;">[(ngModel)]="textColor"</span><span style="color: #204a87; font-weight: bold;">></span>
<span style="color: #204a87; font-weight: bold;"><table</span> <span style="color: #c4a000;">border=</span><span style="color: #4e9a06;">2</span><span style="color: #204a87; font-weight: bold;">></span>
<span style="color: #8f5902; font-style: italic;"><!-- expression calculates colspan=2 --></span>
<span style="color: #204a87; font-weight: bold;"><tr></span>
<span style="color: #204a87; font-weight: bold;"><td</span> <span style="border: 1px solid #ef2929; color: #a40000;">[attr.colspan]="1</span> <span style="border: 1px solid #ef2929; color: #a40000;">+</span> <span style="border: 1px solid #ef2929; color: #a40000;">1</span> <span style="border: 1px solid #ef2929; color: #a40000;">+</span> <span style="border: 1px solid #ef2929; color: #a40000;">1"</span><span style="color: #204a87; font-weight: bold;">></span>Left - Center - Right<span style="color: #204a87; font-weight: bold;"></td></span>
<span style="color: #204a87; font-weight: bold;"></tr></span>
<span style="color: #204a87; font-weight: bold;"><tr></span>
<span style="color: #204a87; font-weight: bold;"><td></span>1<span style="color: #204a87; font-weight: bold;"></td></span>
<span style="color: #204a87; font-weight: bold;"><td></span>2<span style="color: #204a87; font-weight: bold;"></td></span>
<span style="color: #204a87; font-weight: bold;"><td></span>3<span style="color: #204a87; font-weight: bold;"></td></span>
<span style="color: #204a87; font-weight: bold;"></tr></span>
<span style="color: #204a87; font-weight: bold;"></table></span>
</pre>
</div>
<h3 style="text-align: left;">
</h3>
<h3 style="text-align: left;">
Live Code </h3>
Plunker here:
<a href="https://embed.plnkr.co/plunk/BT8gj5?show=app,preview">https://embed.plnkr.co/plunk/BT8gj5?show=app,preview</a>
</div>
Witspry Technovatehttp://www.blogger.com/profile/13599435720165810309noreply@blogger.com1