<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Cornilov Dan on Medium]]></title>
        <description><![CDATA[Stories by Cornilov Dan on Medium]]></description>
        <link>https://medium.com/@dancornilov?source=rss-95f24988566a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6E7pHn4M_ILK8SxmIwt_gA.jpeg</url>
            <title>Stories by Cornilov Dan on Medium</title>
            <link>https://medium.com/@dancornilov?source=rss-95f24988566a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 08:36:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dancornilov/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Angular’s trackBy —  easier than ever]]></title>
            <link>https://medium.com/angular-magic/angulars-trackby-easier-than-ever-89e973389487?source=rss-95f24988566a------2</link>
            <guid isPermaLink="false">https://medium.com/p/89e973389487</guid>
            <category><![CDATA[angular-performance]]></category>
            <category><![CDATA[ngfor]]></category>
            <category><![CDATA[trackby]]></category>
            <category><![CDATA[angular-best-practices]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Cornilov Dan]]></dc:creator>
            <pubDate>Tue, 27 Jun 2023 10:08:51 GMT</pubDate>
            <atom:updated>2023-06-27T10:08:51.171Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular’s trackBy — easier than ever</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aNPw7LzC3pAE_0JPwqbr4A.jpeg" /></figure><p>Using <strong>trackBy</strong> is a typical solution to improve the performance of your Angular application.</p><p>This article does not cover how trackBy works, as there is already sufficient information available on this topic.</p><p>How does ChatGBT explain this?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S-qhaPRnJythhcC2MlK7AA.png" /></figure><h4>Problem</h4><p>Typically, when using <strong>trackBy</strong> in Angular, it is necessary to create a function that generates a unique value for each item. This method should be implemented in every component where trackBy is utilized.</p><p>Let’s suppose we have a couple of components that need to render a list of items.</p><pre>@Component({<br>  selector: &#39;app-cats&#39;,<br>  template: `<br>    &lt;ul&gt; <br>      &lt;li *ngFor=&quot;let item of items; trackBy: trackById&quot;&gt;<br>    &lt;/ul&gt;<br>  `,<br>  styleUrls: [&#39;./cats.component.scss&#39;],<br>})<br>export class CatsComponent {<br>  @Input() items: {id: number; name: string}[];<br><br> trackById(index, item): number {<br>     return item.id; <br>  }<br>}</pre><pre>@Component({<br>  selector: &#39;app-dogs&#39;,<br>  template: `<br>    &lt;ul&gt; <br>      &lt;li *ngFor=&quot;let item of items; trackBy: trackByIndex&quot;&gt;<br>    &lt;/ul&gt;<br>  `,<br>  styleUrls: [&#39;./dogs.component.scss&#39;],<br>})<br>export class DogsComponent {<br>  @Input() items: string[];<br><br> trackByIndex(index, item): number {<br>     return item.index; <br>  }<br>}</pre><p>As we can observe, there is a significant amount of boilerplate code that can be minimized.</p><h4>Solution</h4><p>To avoid code duplication and enhance the usability of trackBy, we employ a helpful technique known as PerformanceUtils.</p><pre>export class PerformanceUtils {<br>  static trackById(_index: number, item: any): string {<br>    return item.id;<br>  }<br><br>  static trackByIndex(index: number): number {<br>    return index;<br>  }<br>}</pre><p>Subsequently, the PerformanceUtils can be declared as a class property and utilized directly within the template.</p><pre>@Component({<br>  selector: &#39;app-cats&#39;,<br>  template: `<br>    &lt;ul&gt; <br>      &lt;li *ngFor=&quot;let item of items; trackBy: PerformanceUtils.trackById&quot;&gt;<br>    &lt;/ul&gt;<br>  `,<br>  styleUrls: [&#39;./cats.component.scss&#39;],<br>})<br>export class CatsComponent {<br>  @Input() items: {id: number; name: string}[];<br><br>  PerformanceUtils: typeof PerformanceUtils = PerformanceUtils;<br>}</pre><pre>@Component({<br>  selector: &#39;app-dogs&#39;,<br>  template: `<br>    &lt;ul&gt; <br>      &lt;li *ngFor=&quot;let item of items; trackBy: PerformanceUtils.trackByIndex&quot;&gt;<br>    &lt;/ul&gt;<br>  `,<br>  styleUrls: [&#39;./dogs.component.scss&#39;],<br>})<br>export class DogsComponent {<br>  @Input() items: string[];<br><br>  PerformanceUtils: typeof PerformanceUtils = PerformanceUtils;<br>}</pre><p>As we can see we have a lot of boilerplate code, which can be reduced, and now is very easy to integrate trackBy in every *ngFor of your application has become effortless by simply declaring one additional property.</p><p><strong>Connect with us on social media:<br></strong>🙉 Visit us on our website: <a href="https://angularmagic.com/">AngularMagic.com</a><br>🙈 Follow us on LinkedIn: <a href="https://www.linkedin.com/company/angular-magic/">LinkedIn</a><br>🙊 Follow us on Telegram: <a href="https://t.me/+e02uqe-wcsFhZjYy">Join link</a></p><p>🤌 Stay updated with our latest news, articles, and updates by following us on these platforms. We appreciate your support!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89e973389487" width="1" height="1" alt=""><hr><p><a href="https://medium.com/angular-magic/angulars-trackby-easier-than-ever-89e973389487">Angular’s trackBy —  easier than ever</a> was originally published in <a href="https://medium.com/angular-magic">Angular Magic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Camera Capture — Smile]]></title>
            <link>https://medium.com/@dancornilov/angular-camera-capture-smile-436d15f1ae1b?source=rss-95f24988566a------2</link>
            <guid isPermaLink="false">https://medium.com/p/436d15f1ae1b</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[camera-capture]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-camera-capture]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Cornilov Dan]]></dc:creator>
            <pubDate>Thu, 19 Sep 2019 14:04:09 GMT</pubDate>
            <atom:updated>2019-09-29T06:33:16.528Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular Camera Capture — Smile</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fObWdPEzp6qWkcvlVRrefg.jpeg" /></figure><p>Greetings my friends. Just finished another good project and added to my “experience collection” with interesting features. One of the project’s functionalities was “identity confirmation”. This functionality forces user to make a selfie in order to get the identity confirmation in real time.</p><p>So, how I solved this request feature?! First of all, I did a small research about camera functionality. I found an existent solution, but a third party module inside the project is another risk and dependency. This was the reason why I chose custom implementation.</p><p>Nowadays, cyber security is one of the most important things to pay attention to. In since next the component for identifying user is related to security, we need to foresee multiple use-cases.</p><h3>Desktop Capture</h3><p>We will use getUserMedia to receive access to user’s media device.</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia">MediaDevices.getUserMedia()</a></p><h3>Mobile Capture</h3><p>Capturing on mobile devices it’s a little harder than on desktop. One solution is to attribute capture for input, which activates camera on mobile devices.</p><pre>&lt;input type=&quot;file&quot; accept=&quot;image/*&quot; capture=&quot;camera&quot; (change)=&quot;onFileSelected($event)&quot;/&gt;</pre><p><a href="https://w3c.github.io/html-media-capture/">HTML Media Capture</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FjUil0w7QSfEPm7Fysn%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FjUil0w7QSfEPm7Fysn&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FjUil0w7QSfEPm7Fysn%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="286" frameborder="0" scrolling="no"><a href="https://medium.com/media/b90251ed553c2caee7b2a1a7dde9f01d/href">https://medium.com/media/b90251ed553c2caee7b2a1a7dde9f01d/href</a></iframe><p>Finally, we can use this component for different use-cases, follow your created mind.</p><p><strong>Thanks for attention, waiting for your feedback.</strong></p><p><a href="https://github.com/dancornilov/camera-capture">dancornilov/camera-capture</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=436d15f1ae1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular 7 Global Validators — Almost perfect]]></title>
            <link>https://medium.com/@dancornilov/angular-7-global-validators-almost-perfect-3fd15165ec54?source=rss-95f24988566a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fd15165ec54</guid>
            <category><![CDATA[ngx-translate]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[global-validator]]></category>
            <category><![CDATA[validator]]></category>
            <category><![CDATA[reactive-forms]]></category>
            <dc:creator><![CDATA[Cornilov Dan]]></dc:creator>
            <pubDate>Wed, 27 Mar 2019 15:39:04 GMT</pubDate>
            <atom:updated>2022-01-28T13:54:10.015Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular 7 Global Validators — Almost perfect</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nsYTn_232jFgYaTGLBVGfw.jpeg" /></figure><p>Hi everyone, finally I found the a smart solution for display input’s validation messages. If you want to make your “coding” life easier then you are in the right place.</p><h3>1.Install and configure all dependencies</h3><p>We can create custom interpolation pipe, but in order not to reinvent the wheel, we will use <a href="http://www.ngx-translate.com/">ngx-translate</a>. We’ll have just benefits from using this module.</p><ol><li>Internalization</li><li>Reusable strings</li><li>Soft coded</li></ol><p>First of all, we need to install it. In their documentation you can find installation steps and other useful information.</p><h4>Install <a href="http://www.ngx-translate.com/">ngx-translate</a></h4><pre>npm install @ngx-translate/core --save<br>npm install @ngx-translate/http-loader</pre><p>In the end, our app module should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c565da0698f3f421fc42424563036dc0/href">https://medium.com/media/c565da0698f3f421fc42424563036dc0/href</a></iframe><h4>Set default language</h4><p>In our <strong>app.component.ts </strong>we inject <strong>TranslateService</strong> &amp; set default language.</p><pre>constructor(private translate: TranslateService) {           </pre><pre>    translate.setDefaultLang(&#39;en&#39;);  <br>}</pre><p>Please don’t forget about <strong>TranslateService</strong> import.</p><pre>import { TranslateService } from &#39;@ngx-translate/core&#39;;</pre><h4>Create json with translations</h4><p>JSON files with translations should be located in <strong>i18n</strong> folder:</p><pre>src/assets/i18n</pre><p>Create <strong>en.json </strong>file with validations messages.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d3738b66a138b1d068613816c1b8ecb/href">https://medium.com/media/8d3738b66a138b1d068613816c1b8ecb/href</a></iframe><p>This is a simple <strong>json</strong> file that will be loaded by our <strong>TranslateHttpLoader</strong> which we created.</p><h3>2.Validator Component</h3><p>We create separate <strong>“smart”</strong> component which will contain all validations, transformations and all this staff. We’ll use validator component together with <a href="https://angular.io/guide/reactive-forms">Reactive Forms</a> &amp; <a href="https://angular.io/guide/reactive-forms#simple-form-validation">Form Validations</a>. One validator is related to one FormControl . Depending on control validations, we will show related validation message. Would be perfect if we’ll create our component in <strong>SharedModule. <br></strong><em>(In </em><a href="http://www.ngx-translate.com/"><em>ngx-translate</em></a><em> documentation, you can find how use TranslateService if you have SharedModule)</em></p><h4>Create Validator Component</h4><pre>ng g c validator</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5a181e397f3ed788f30002f6c111ae5/href">https://medium.com/media/b5a181e397f3ed788f30002f6c111ae5/href</a></iframe><h4>How will our validator component work?</h4><p>For example, we have next form:</p><pre>this.formBuilder.group({<br>  <strong>name</strong>: [null, Validators.required],<br>  <strong>age</strong>: [null, Validators.required]<br>});</pre><p>When user doesn’t fill name, our validator should print:Name is required! <br>Same message should be printed if user didn’t fill age field, but with different name: Age is required!</p><p>Global purpose of <strong>Validator component </strong>is to print validation message related of field name and field validators.</p><h4>Assign field names</h4><p>We created separate fields object in en.json for all fields name.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5063023755928eb432bf4ab911cccc43/href">https://medium.com/media/5063023755928eb432bf4ab911cccc43/href</a></iframe><h4>Extract FormControl name</h4><p>Usually, FormControl name is similar with field label or field name which is showed to user. <br>It will extract field name from FormControl, but will create customName variable for use custom name for field, for better flexibility.</p><pre>@Input() <strong>public</strong> customName: <strong>string</strong>;</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91d4733d8ad57db27f298d634daf6b1b/href">https://medium.com/media/91d4733d8ad57db27f298d634daf6b1b/href</a></iframe><h4>Get “pretty” field name</h4><p>FormControl name or customName is just a key, which helps us to find<strong> “pretty” </strong>field name in fields object from en.json . We use <strong>TranslateService</strong> instant() method for obtain field name. In ngOnInit() lifecycle we check if this <strong>Validator</strong> use custom name.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4981ffb35f2b9b3aa8ac8cc9b98a616/href">https://medium.com/media/b4981ffb35f2b9b3aa8ac8cc9b98a616/href</a></iframe><h4>Create simple &amp; custom validation message</h4><p>Last step for finishing our Validator component is to create dynamically validation message. At the moment, we have field name and control .</p><p>For custom validation message we need separate variable. This will contain validation name and text which will be displayed like validation message.</p><pre>@Input() <strong>public </strong>customValidation: { name: <strong>string</strong>, text: <strong>string </strong>}</pre><p>FormControl has property errors . We extract these errors and check if this validator doesn’t have custom validation message.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24b17c1b7e8181bee38eb97cba41e6e8/href">https://medium.com/media/24b17c1b7e8181bee38eb97cba41e6e8/href</a></iframe><h4>Final version of Validator component</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/078f209c7e476eef48fc2a9aa2680dbd/href">https://medium.com/media/078f209c7e476eef48fc2a9aa2680dbd/href</a></iframe><h4>Create validator markup &amp; styles</h4><p>There are some reasons why we don’t use <strong>loop </strong>to optimize this markup<strong>. </strong>Validation message will be displayed just when user touches or writes something in field.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c912c89d0cd6d4ed3ded8541a97bfde3/href">https://medium.com/media/c912c89d0cd6d4ed3ded8541a97bfde3/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2e98159f6603ec4fef5763b64daafbf/href">https://medium.com/media/b2e98159f6603ec4fef5763b64daafbf/href</a></iframe><h3>How to use it?</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e408c1390d64e46418241fbce3c9a59b/href">https://medium.com/media/e408c1390d64e46418241fbce3c9a59b/href</a></iframe><p>Now, when we’ll create a form and want to show validation messages, we just use <strong>Validator Component.</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F6wp6MQrLHBNBwWMPSh%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2F6wp6MQrLHBNBwWMPSh&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F6wp6MQrLHBNBwWMPSh%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="338" frameborder="0" scrolling="no"><a href="https://medium.com/media/15b741ccc9546d45bdfb96fa8ab9857c/href">https://medium.com/media/15b741ccc9546d45bdfb96fa8ab9857c/href</a></iframe><p><a href="https://github.com/dancornilov/validator">GitHub Angular app with working example.</a></p><p><strong>Thanks for attention, waiting for your feedback.</strong></p><p><strong>NPM Package:</strong> <a href="https://www.npmjs.com/package/@angular-magic/ngx-validator">https://www.npmjs.com/package/@angular-magic/ngx-validator</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fd15165ec54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular 5 Loader Component — It’s simple]]></title>
            <link>https://medium.com/@dancornilov/angular-5-loader-component-its-simple-a98381f8b9c2?source=rss-95f24988566a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a98381f8b9c2</guid>
            <category><![CDATA[angular-tutoarial]]></category>
            <category><![CDATA[angular-loader]]></category>
            <category><![CDATA[loader-component]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-loader-component]]></category>
            <dc:creator><![CDATA[Cornilov Dan]]></dc:creator>
            <pubDate>Thu, 24 Jan 2019 07:43:35 GMT</pubDate>
            <atom:updated>2019-01-24T07:43:35.955Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular 5 Loader Component — It’s simple</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NyxwaiCtlBAUi-XfEvEi0A.jpeg" /></figure><p>Hi everyone ! I’ve decided to create it because when I needed something like that, I didn’t find one good article. This one will tell you how to create a simple loader component from A to Z.</p><p>Let’s begin.<br>First of all we need to create a module which contains a loader component and other related things.</p><pre>ng g m loader</pre><p>Inside loader module we should create loader component &amp; loader service.</p><pre>ng g c loader</pre><pre>ng g s loader</pre><p>Declare and export LoaderComponent , add LoaderService in providers.<br>Our module should look like the one from this example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2813b2737f1a1c164a211b3abd95a115/href">https://medium.com/media/2813b2737f1a1c164a211b3abd95a115/href</a></iframe><p>Now let’s create the loader itself. You can make your personal loader, but I will use an example from google.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*4t4Gwh1yxhxM0tJJsgRk8g.gif" /><figcaption><a href="https://codepen.io/WebSonata/pen/bRaONB">Demo (with code)</a></figcaption></figure><p>It will be nice for you to use this loader. When you understand how it works, you will adapt the loader to your project.</p><p>You just need to copy markup and styles.</p><p>Please put class instead of id in your markup. <br>We’ll have two types of loader — global which will be on full screen and secondary which will appear inside an element. For this, create two new classes global and secondary .</p><p>I adopted css in scss.<em>(If you need </em><em>css please use code from demo).</em>Your markup and styles probably looks like the one from this examples.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7796154e61ea300f1d476dbef0c99d5b/href">https://medium.com/media/7796154e61ea300f1d476dbef0c99d5b/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d068080721a89d48eed9d5e1e2b6655b/href">https://medium.com/media/d068080721a89d48eed9d5e1e2b6655b/href</a></iframe><h3>Create Loader Service Logic</h3><p>Inside loader.service.ts we need to create an <strong>BehaviorSubject</strong> which contains loader’s id and status .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e593a2c94ab5ae75c035bfecffe14c6a/href">https://medium.com/media/e593a2c94ab5ae75c035bfecffe14c6a/href</a></iframe><p>In our service we have just two methods. First method is showLoader(id) which has parameter id , by default id is global . It means — if we call showLoader() without id , we automatically will call global loader which will fill the whole screen.<br>Another method is vice versa ,hideLoader(id) just hides active loader.</p><p>We need to understand when we show and hide loader. <strong>Observable </strong>will solve this issue.loaderStatus$ is our <strong>Observable</strong> to which we can subscribe and make show/hide actions in LoaderComponent.</p><h4>Create loader model</h4><p>Create a new file loader.model.ts which contains loader interface.</p><pre><strong>export interface </strong>Loader {<br>  id: <strong>string</strong>;<br>  status: <strong>boolean</strong>;<br>}</pre><h3>Connect Component with Service</h3><p>In our component we should inject our service in constructor . Create two variables: id with @Input decorator and show which displays and hides our loader.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d802a94882c29918105d06641531875/href">https://medium.com/media/1d802a94882c29918105d06641531875/href</a></iframe><p>We use @Input decorator because we need to give id for each loader that we create.</p><p>In ngOnInit() lifecycle we subscribe to loaderStatus$ .</p><p>To use multiple loaders we need to make a lot of validations. First one: check if loader’s id is equal with id which we receive from loaderStatus$ . Second validation: we check loader status .</p><p>If all validations are passed, then we show loader.</p><blockquote>“We can see the fruits of our effort”</blockquote><p>Now, to use loader we just need to use it in our template and call. After injecting loader service in constructor , to show loader use showLoader() method.</p><pre>// Template<br>&lt;app-loader&gt;&lt;/app-loader&gt;</pre><pre>// TypeScript<br>this.loaderService.showLoader();</pre><p>If you want to have multiple loader’s in your component just put id for each loader.</p><pre>&lt;div class=&quot;loaders&quot;&gt;<br>  &lt;div class=&quot;first&quot;&gt;<br>    &lt;app-loader [id]=&quot;&#39;first&#39;&quot;&gt;&lt;/app-loader&gt;<br>    &lt;h1&gt;First container&lt;/h1&gt;<br>  &lt;/div&gt;</pre><pre>  &lt;div class=&quot;second&quot;&gt;<br>    &lt;app-loader [id]=&quot;&#39;second&#39;&quot;&gt;&lt;/app-loader&gt;<br>    &lt;h1&gt;Second container&lt;/h1&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p><em>Remember — </em><em>first and </em><em>second classes should have </em><em>position: relative ;</em></p><p>Send loader’s id in showLoader method to show loader.</p><pre>this.loaderService.showLoader(&#39;first&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*tgXE64RBeLrKkG7SedDRnw.gif" /></figure><p><a href="https://github.com/dancornilov/loader-component">GitHub project, to see full example.</a></p><p><strong>Thanks for attention, waiting for your feedback.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a98381f8b9c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular 5 Http Interceptors — Do More]]></title>
            <link>https://medium.com/@dancornilov/angular-5-http-interceptors-do-more-dbf63b0791ac?source=rss-95f24988566a------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbf63b0791ac</guid>
            <category><![CDATA[token-http-interceptor]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[http-interceptors]]></category>
            <category><![CDATA[angular-5]]></category>
            <category><![CDATA[http-request]]></category>
            <dc:creator><![CDATA[Cornilov Dan]]></dc:creator>
            <pubDate>Fri, 28 Dec 2018 07:37:20 GMT</pubDate>
            <atom:updated>2018-12-28T07:37:20.285Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular 5 Http Interceptors — Do More</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PB9cbu4jXHh58BpArRVxXg.png" /></figure><p>Hi everyone, in this article I will show you just some HttpInterceptors which will ease your life and will make your code cleanable &amp; readable.</p><p>So, HttpInterceptors have next benefits:</p><ol><li>Improve aesthetics of the code.</li><li>Optimize working process.</li><li>Automate some flows.</li></ol><h3>Environment HttpInterceptor</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*4RXjOKCpQNiIqCqVcf0yVg.jpeg" /></figure><p>Usually, application has different environments . Depending on the app, we use different serverName. For optimizing this process environment variable is used.</p><pre>// Without Http Interceptor<br>this.http.get(environment.serverName + &#39;api/get&#39;);</pre><pre>// With Http Interceptor<br>this.http.get(&#39;api/get&#39;);</pre><p>How do you think, which option is better? Looks more cleanable?</p><blockquote>If we use HttpInterceptor we concatenate serverName “<a href="https://medium.com/@dancornilov/angular-5-loader-http-interceptor-just-once-94a7c3c00d35">Just Once</a>” in our code.</blockquote><p>First HttpInterceptor concatenate serverName to each request.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0a17c0b56d27704083bb6b428469b4a/href">https://medium.com/media/b0a17c0b56d27704083bb6b428469b4a/href</a></iframe><h3>Token HttpInterceptor</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XyJgtrjdlONnJrqrBi7Ibg.jpeg" /></figure><p>In every project I have worked, I have used <a href="https://jwt.io/">JWT</a> token. This was a reason why I have created this HttpInterceptor . Usually, private endpoints require token. An easy way to send token in Request Header is to use HttpInterceptor . It automatically sends token , if it exists in our storage.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b0cc663afffae6980cc4c4f07f76d6b/href">https://medium.com/media/7b0cc663afffae6980cc4c4f07f76d6b/href</a></iframe><p>Second HttpInterceptor sets token in Request Header if it exists.</p><h3>Status HttpInterceptor</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*zrtKqduNjZVxaE5zaH5JDQ.jpeg" /></figure><p>Each request has response code. Depending on the status code we can make some actions. For example, if we have 404 we can redirect user to <a href="https://www.google.com/search?q=404+page&amp;rlz=1C5CHFA_enMD777MD777&amp;source=lnms&amp;tbm=isch&amp;sa=X&amp;ved=0ahUKEwi66bKkusDfAhVCJFAKHVPfAKcQ_AUIDigB&amp;biw=1440&amp;bih=790">404 page not found</a>. If our app has different user roles (simple &amp; premium) we can redirect user to page where he can subscribe to some plan (usually permission denied return 403 code).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f74b7c4b3bf59215489fae24cdaddfb0/href">https://medium.com/media/f74b7c4b3bf59215489fae24cdaddfb0/href</a></iframe><p>Last but not least, we need to declare our HttpInterceptor in NgModule providers . Of course we can combine this elements.</p><pre>providers: [<br>  {<br>    provide: HTTP_INTERCEPTORS,<br>    useClass: TokenInterceptor,<br>    multi: <strong>true<br>  </strong>},<br>  {<br>    provide: HTTP_INTERCEPTORS,<br>    useClass: StatusInterceptor,<br>    multi: <strong>true<br>  </strong>},<br>  {<br>    provide: HTTP_INTERCEPTORS,<br>    useClass: EnvironmentInterceptorService,<br>    multi: <strong>true<br>  </strong>}<br>]</pre><p>Everything depends on your application/on your business vision. If at least one will be useful I will be happy.</p><p><strong>Thanks for attention, waiting for your feedback.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbf63b0791ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular 5 Loader Http Interceptor — Just Once]]></title>
            <link>https://medium.com/@dancornilov/angular-5-loader-http-interceptor-just-once-94a7c3c00d35?source=rss-95f24988566a------2</link>
            <guid isPermaLink="false">https://medium.com/p/94a7c3c00d35</guid>
            <category><![CDATA[angular-5]]></category>
            <category><![CDATA[http-interceptors]]></category>
            <category><![CDATA[loader-interceptor]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Cornilov Dan]]></dc:creator>
            <pubDate>Wed, 12 Sep 2018 20:57:45 GMT</pubDate>
            <atom:updated>2018-09-12T20:57:45.012Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G-BBXe8a26tKRMXi2ZbC3g.jpeg" /></figure><p>Each application uses <strong>APIs</strong> (application programming interface). Every time we use it, we should show users that they need to wait, while making a request. When I first started working with API, I used the loader methods in three different places.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*blF3-sYGV9DJkfa-AdTBsg.jpeg" /></figure><p>Before sending the request and after it was made. This thing is repeated to each sent request. After a while, I have noticed that writing three lines of code at each request is a little annoying. Sometimes I can forget to do this, that is why I have found a solution.</p><h3>Http Interceptor</h3><p>What is <a href="https://angular.io/api/common/http/HttpInterceptor">HttpInterceptor</a>? In my opinion this is an one of reason Why I use Angular. This tool helps us to forget about loader’s methods. What we should do? It’s easy — create one <strong>HttpInterceptor</strong> which activates loader before sending some request and hides loader when it receives success or error response.</p><h3>Dependencies</h3><p>Before we create an interceptor we should import <a href="https://angular.io/api/common/http/HttpClientModule">HttpClientModule</a> if we haven’t done it yet.</p><pre><strong>import </strong>{ HttpClientModule } <strong>from </strong>&quot;@angular/common/http&quot;;</pre><pre>@NgModule({<br>  imports: [<br>CommonModule, <br>HttpClientModule // Import this module<br>],<br>  declarations: [],<br>  providers: []<br>})<br><strong>export class </strong>AppModule {}</pre><h3>Creating HttpInterceptor</h3><pre>ng g class loader-interceptor</pre><p>After we create this class we should implements HttpInterceptor for implementing interfaces. It requires the class to have the methods which are defined in the implemented interfaces. We have to mark this class as an <a href="https://angular.io/api/core/Injectable">Injectable</a>.</p><pre><strong>import </strong>{HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} <strong>from </strong>&#39;@angular/common/http&#39;;<br><strong>import </strong>{Injectable} <strong>from </strong>&#39;@angular/core&#39;;<br><strong>import </strong>{Observable} <strong>from </strong>&#39;rxjs/Observable&#39;;<br><br>@Injectable()<br><strong>export class </strong>LoaderInterceptor <strong>implements </strong>HttpInterceptor {<br><br>  intercept(request: HttpRequest&lt;<strong>any</strong>&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;<strong>any</strong>&gt;&gt; {<br>    <strong>return </strong>next.handle(request);<br>  }<br>}</pre><p>Last thing which we should do is — when we receive a response, we always need to hide the loader. We can differentiate success and error response and we can do some things depending on the error code. I will give an example in order to illustrate my point of view:<br>- When we have <strong>401 code </strong>we can logout user.<br>- When we have <strong>404</strong> <strong>code</strong> we can redirect him to Not Found page.<br>- When we have some bad request we can show notification toaster or note.</p><pre><strong>import </strong>{HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} <strong>from </strong>&#39;@angular/common/http&#39;;<br><strong>import </strong>{Injectable} <strong>from </strong>&#39;@angular/core&#39;;<br><strong>import </strong>{Observable} <strong>from </strong>&#39;rxjs/Observable&#39;;<br><strong>import </strong>{Router} <strong>from </strong>&#39;@angular/router&#39;;<br><br>@Injectable()<br><strong>export class </strong>LoaderInterceptor <strong>implements </strong>HttpInterceptor {<br>  <strong>constructor</strong>(<strong>private </strong>router: Router) {<br>  }<br><br>  intercept(request: HttpRequest&lt;<strong>any</strong>&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;<strong>any</strong>&gt;&gt; {<br>    // Activate loader<br>    console.log(&#39;before request sent&#39;);<br>    <strong>return </strong>next.handle(request).do((event: HttpEvent&lt;<strong>any</strong>&gt;) =&gt; {<br>      <strong>if </strong>(event <strong>instanceof </strong>HttpResponse) {<br>        // Hide loader when receive success response<br>        console.log(&#39;when receive success&#39;);<br>      }<br>    }, (err: <strong>any</strong>) =&gt; {<br>      <strong>if </strong>(err <strong>instanceof </strong>HttpErrorResponse) {<br>        <strong>switch </strong>(err.status) {<br>          <strong>case </strong>401:<br>            // Logout &amp; redirect to home page<br>            <strong>this</strong>.router.navigate([&#39;/&#39;]);<br>            <strong>break</strong>;<br>          <strong>default</strong>:<br>            // Hide loader when receive error response<br>            console.log(&#39;when receive error&#39;);<br>            <strong>break</strong>;<br>        }<br>      }<br>    });<br>  }<br>}</pre><h3>HttpInterceptor Declaration</h3><p>Go to our module and declare this service in providers.</p><pre>providers: [<br>    {<br>      provide: HTTP_INTERCEPTORS,<br>      useClass: LoaderInterceptor,<br>      multi: <strong>true<br>    </strong>}<br>]</pre><h3>Conclusion</h3><p>Brevity is the soul of wit, we have to use loader’s methods only once in interceptor. It helps us to manage easy the process, depending on our scope.</p><p>Good Luck!</p><p><strong>Thanks for attention, waiting for your feedback.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94a7c3c00d35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular 5 Color Picker Component — Be colorfully]]></title>
            <link>https://medium.com/@dancornilov/angular-5-color-picker-component-be-colorfully-7e8b12c27ac0?source=rss-95f24988566a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e8b12c27ac0</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[color-picker]]></category>
            <category><![CDATA[angular-color-picker]]></category>
            <category><![CDATA[angular-5]]></category>
            <category><![CDATA[color-palette]]></category>
            <dc:creator><![CDATA[Cornilov Dan]]></dc:creator>
            <pubDate>Tue, 04 Sep 2018 20:00:26 GMT</pubDate>
            <atom:updated>2019-01-22T15:50:58.017Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kN6CeLilkZVV3waqNxv0OA.jpeg" /></figure><p>Hi people! Now I am working on really interesting project. It is supposed that people can choose the color that they want to be on their profile. For solving this problem I have created a simple color picker which has 25 colors by default and has possibility to add color from HEX code. If you want to have simple, original and exceptional color picker, you’ve come to the right place. I will show how you can implement this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lsT2bDOdSwsUPl6P89615w.jpeg" /></figure><p>First of all we should create a new component, I call it “color-picker”.</p><pre>ng g c color-picker</pre><p>We should declare and export this component in module.</p><h3>Defining default colors</h3><p>We can decrease the number of default colors, but in my case I have 25 colors.</p><pre><strong>export class </strong>ColorPickerComponent {<br>  <strong>public </strong>defaultColors: <strong>string</strong>[] = [<br>    &#39;#ffffff&#39;,<br>    &#39;#000105&#39;,<br>    &#39;#3e6158&#39;,<br>    &#39;#3f7a89&#39;,<br>    &#39;#96c582&#39;,<br>    &#39;#b7d5c4&#39;,<br>    &#39;#bcd6e7&#39;,<br>    &#39;#7c90c1&#39;,<br>    &#39;#9d8594&#39;,<br>    &#39;#dad0d8&#39;,<br>    &#39;#4b4fce&#39;,<br>    &#39;#4e0a77&#39;,<br>    &#39;#a367b5&#39;,<br>    &#39;#ee3e6d&#39;,<br>    &#39;#d63d62&#39;,<br>    &#39;#c6a670&#39;,<br>    &#39;#f46600&#39;,<br>    &#39;#cf0500&#39;,<br>    &#39;#efabbd&#39;,<br>    &#39;#8e0622&#39;,<br>    &#39;#f0b89a&#39;,<br>    &#39;#f0ca68&#39;,<br>    &#39;#62382f&#39;,<br>    &#39;#c97545&#39;,<br>    &#39;#c1800b&#39;<br>  ];<br>}</pre><p>Our color picker should accept and return user’s picked color. For this we use <a href="https://angular.io/api/core/Input">Input</a> and <a href="https://angular.io/api/core/Output">Output</a><strong>.</strong></p><pre><strong>import </strong>{ EventEmitter, Input, Output } <strong>from </strong>&#39;@angular/core&#39;;</pre><pre><strong>export class </strong>ColorPickerComponent <strong>implements </strong>OnInit {<br>  @Input() heading: <strong>string</strong>;<br>  @Input() color: <strong>string</strong>;<br>  @Output() event = <strong>new </strong>EventEmitter();<br>}</pre><p>In variable “<strong>heading</strong>” it will come a title of color picker. In our example this is “Background”. Color picked by user will come in “<strong>color”</strong> variable, “<strong>event</strong>” is a new <a href="https://angular.io/api/core/EventEmitter">EventEmitter</a> which returns the color selected by the user.</p><h3>Creating color picker basic carcass</h3><p>This is basic HTML code</p><pre>&lt;div class=&quot;color-picker&quot;&gt;<br>  &lt;div class=&quot;summary-info&quot;&gt;<br>    &lt;div class=&quot;info&quot;&gt;<br>      &lt;p class=&quot;style&quot;&gt;{{ heading }}&lt;/p&gt;<br>      &lt;p class=&quot;style-value&quot;&gt;{{ color }}&lt;/p&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;circle&quot;&gt;&lt;/div&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;opened&quot;&gt;<br>    &lt;div class=&quot;colors&quot;&gt;<br>      &lt;div *ngFor=&quot;let paint of defaultColors&quot; class=&quot;circle&quot;&gt;&lt;/div&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;hex-code&quot;&gt;<br>      &lt;p&gt;Hex Code&lt;/p&gt;<br>      &lt;div class=&quot;g-input&quot;&gt;<br>        &lt;input type=&quot;text&quot; maxlength=&quot;7&quot; [value]=&quot;color&quot; /&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p><a href="https://codepen.io/dan-cornilov/pen/xardgd">Click here to view demo</a> with HTML markup without actions and logic. Here you can find styles.</p><p>Now we should fill the circles. <a href="https://angular.io/api/common/NgStyle">NgStyle</a> directive helps us to solve this issue. We use it for both divs with class “circle” . For main circle or picked color circle we use color from variable.</p><pre>&lt;div class=&quot;circle&quot; [ngStyle]=&quot;{&#39;background&#39;: color}&quot;&gt;&lt;/div&gt;</pre><pre>&lt;div *ngFor=&quot;let paint of defaultColors&quot; class=&quot;circle&quot; [ngStyle]=&quot;{&#39;background&#39;: paint}&quot;&gt;&lt;/div&gt;</pre><h3>Creating functionality</h3><p>Firstly we create variable which will open and close color picker’s dropdown section.</p><pre><strong>public</strong> show = false;</pre><p>We can make directly in HTML toggle process, it is better to make this logic in javascript.</p><pre><em>/**<br> * Change status of visibility to color picker<br> */<br></em><strong>public </strong>toggleColors() {<br>  <strong>this</strong>.show = !<strong>this</strong>.show;<br>}</pre><p>Last think is to implement this in HTML, put to div with class “summary-info” click action, and for div with class “opened” condition.</p><pre>&lt;div class=&quot;summary-info&quot; (click)=&quot;toggleColors()&quot;&gt;<br>&lt;div class=&quot;opened&quot; *ngIf=&quot;show&quot;&gt;</pre><p>Now when we click to summary section our dropdown section will open.</p><h3>Creating logic</h3><p>We have two ways of color picking. When user clicks to circle from default colors or when introduces HEX code in field. Literally, that means that we have to ensure that they use a valid HEX code, we use a simple regex. When color is changed we return “<strong>color</strong>” variable.</p><pre><em>/**<br> * Change color from default colors<br> * </em><strong><em>@param </em></strong><em>{string} color<br> */<br></em><strong>public </strong>changeColor(color: <strong>string</strong>) {<br>  <strong>this</strong>.color = color;<br>  <strong>this</strong>.event.emit(<strong>this</strong>.color); // Return color<br>  <strong>this</strong>.show = <strong>false</strong>;<br>}<br><br><br><em>/**<br> * Change color from input<br> * </em><strong><em>@param </em></strong><em>{string} color<br> */<br></em><strong>public </strong>changeColorManual(color: <strong>string</strong>) {<br>  <strong>const </strong>isValid = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(color);<br><br>  <strong>if </strong>(isValid) {<br>    <strong>this</strong>.color = color;<br>    <strong>this</strong>.event.emit(<strong>this</strong>.color); // Return color<br>  }<br>}</pre><p>Implement this method in our HTML template. When we click to any circle we change current color with circle’s color. If field’s value has a valid HEX code we assign new color. I use action <strong>(keydown.enter)</strong> for closing dropdown section.</p><pre>&lt;div (click)=&quot;changeColor(paint)&quot; *ngFor=&quot;let paint of defaultColors&quot; class=&quot;circle&quot;<br>     [ngStyle]=&quot;{&#39;background&#39;: paint}&quot;&gt;&lt;/div&gt;</pre><pre>&lt;input type=&quot;text&quot; maxlength=&quot;7&quot; [value]=&quot;color&quot; (keyup)=&quot;changeColorManual(paintInput.value)&quot; #paintInput<br>       (keydown.enter)=&quot;toggleColors()&quot;/&gt;</pre><h3>Conclusion</h3><p>This component is easy to use. We only call component and give “<strong>heading</strong>” value and “<strong>color</strong>” value.</p><pre>&lt;app-color-picker [heading]=&quot;&#39;Background&#39;&quot; [color]=&quot;&#39;#FFFFFF&#39;&quot;&gt;&lt;/app-color-picker&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*s58LgdYSGoaRyU2gNwscfA.png" /></figure><p><a href="https://github.com/dancornilov/color-picker">GitHub Angular app with example.</a></p><p><strong>Thanks for attention, waiting for your feedback.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e8b12c27ac0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular 5 Image Uploader Component — API Integration]]></title>
            <link>https://medium.com/@dancornilov/angular-5-image-uploader-component-api-integration-69dadf3e2728?source=rss-95f24988566a------2</link>
            <guid isPermaLink="false">https://medium.com/p/69dadf3e2728</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-5]]></category>
            <category><![CDATA[image-uploader]]></category>
            <category><![CDATA[api-integration]]></category>
            <dc:creator><![CDATA[Cornilov Dan]]></dc:creator>
            <pubDate>Sat, 11 Aug 2018 10:24:43 GMT</pubDate>
            <atom:updated>2018-08-11T11:24:46.824Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lz8VBvDRaXi2sj-fyEg3UQ.png" /></figure><p>Hi everyone, my name is Dan, I’m young Web Developer who passionated by <strong>JavaScript. </strong>Now I am developer on frontend side and make magic things in <a href="https://angular.io/"><strong>Angular</strong></a><strong> 5.</strong> This article is addressed to newbies, this is my first tutorial about programming especially —<em> How to create an image uploader which you will be able to use in your any further project.</em> Okay let’s go.</p><h3>Create new component</h3><p>Usually this component must be placed in shared module, because you should access it globally.</p><pre>ng g c image-uploader</pre><h3>Create simple image uploader</h3><p>After we create a component open <strong>image-uploader.component.html </strong>and create a simple input.</p><pre>&lt;input type=&quot;file&quot; id=&quot;uploader&quot;/&gt;</pre><p>In my case, uploader is a simple icon which is centered in parent block. I use <a href="https://fontawesome.com/?from=io"><strong>FontAwesome</strong></a><strong> </strong><em>(you can replace this with any image or text)</em><strong> </strong>icon and any simple styles.</p><pre>&lt;label class=&quot;uploader-circle&quot;&gt;<br>  &lt;i class=&quot;fas fa-plus&quot;&gt;&lt;/i&gt;<br>  &lt;input type=&quot;file&quot; id=&quot;uploader&quot;/&gt;<br>&lt;/label&gt;</pre><p><em>OPTIONAL: If you want to use </em><a href="https://fontawesome.com/?from=io"><em>FontAwesome</em></a><em> icon import this library in </em><strong>index.html</strong></p><pre>&lt;link rel=&quot;stylesheet&quot; href=&quot;https://use.fontawesome.com/releases/v5.0.8/css/all.css&quot; integrity=&quot;sha384-3AB7yXWz4OeoZcPbieVW64vVXEwADiYyAEhwilzWsLw+9FgqpyjjStpPnpBO8o8S&quot;<br>      crossorigin=&quot;anonymous&quot;&gt;</pre><p>Open <strong>image-uploader.component.scss</strong> and add the following styles:</p><pre>input {<br>  display: none;<br>}<br><br>label.uploader-circle {<br>  $size: 23px;<br>  cursor: pointer;<br>  width: $size;<br>  height: $size;<br>  line-height: 19px;<br>  text-align: center;<br>  border-radius: 100%;<br>  <em>// </em>Using position attribute<em><br>  </em>position: absolute; <em>// Give absolute position<br>  </em>top: 50%; <em>// Vertical center<br>  </em>left: 50%; <em>// Horizontal center<br>  </em>transform: translate(-50%, -50%); <em>// The icon is centered by the style regardless of the size of the parent<br>  </em>transition: all .2s ease-out;<br><br>  i {<br>    font-size: 24px;<br>    color: #000;<br>  }<br>}</pre><p>Now, our image uploader looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/1*4tsw9kivywUVSHFJHew9cA.png" /><figcaption>Image uploader</figcaption></figure><h3>Functionality creation &amp; API connection</h3><p>First of all, we use <strong>HttpClient</strong> for request, for this we import HttpClientModule. For later use of the component, we export it.</p><pre><strong>import </strong>{NgModule} <strong>from </strong>&#39;@angular/core&#39;;<br><strong>import </strong>{CommonModule} <strong>from </strong>&#39;@angular/common&#39;;<br><strong>import </strong>{HttpClientModule} <strong>from </strong>&#39;@angular/common/http&#39;; // Import Path<br><br><br>@NgModule({<br>  imports: [<br>    CommonModule,<br>    HttpClientModule // Import HttpClientModule<br>  ],<br>  declarations: [<br>    ImageUploaderComponent<br>  ],<br>  exports: [<br>    ImageUploaderComponent // Export Image Uplaoder<br>  ],<br>  providers: []<br>})<br><strong>export class </strong>SharedModule {<br>}</pre><p>Second , open <strong>image-uploader.component.ts </strong>and import in constructor HttpClient.</p><pre><strong>import </strong>{Component} <strong>from </strong>&#39;@angular/core&#39;;<br><strong>import </strong>{HttpClient} <strong>from </strong>&#39;@angular/common/http&#39;;<br><br>@Component({<br>  selector: &#39;app-image-uploader&#39;,<br>  templateUrl: &#39;./image-uploader.component.html&#39;,<br>  styleUrls: [&#39;./image-uploader.component.scss&#39;]<br>})<br><strong>export class </strong>ImageUploaderComponent {<br><br>  <strong>constructor</strong>(<strong>private </strong>http: HttpClient) {<br>  }<br><br><br>}</pre><p>Create method which receive uploader params:</p><pre><strong>import </strong>{Component} <strong>from </strong>&#39;@angular/core&#39;;<br><strong>import </strong>{HttpClient} <strong>from </strong>&#39;@angular/common/http&#39;;<br><br>@Component({<br>  selector: &#39;app-image-uploader&#39;,<br>  templateUrl: &#39;./image-uploader.component.html&#39;,<br>  styleUrls: [&#39;./image-uploader.component.scss&#39;]<br>})<br><strong>export class </strong>ImageUploaderComponent {<br><br>  selectedFile: File = <strong>null</strong>;<br><br>  <strong>constructor</strong>(<strong>private </strong>http: HttpClient) {<br>  }<br><br>  <em>/**<br>   * Validate uploader params<br>   * </em><strong><em>@param </em></strong><em>event<br>   */<br>  </em><strong>public </strong>onFileSelected(event) {<br>    <strong>this</strong>.selectedFile = &lt;File&gt;event.target.files[0];<br>    <strong>if </strong>(<strong>this</strong>.selectedFile) {<br>      <strong>// If selected file exist make upload request</strong><br>    }<br>  }<br><br>}</pre><p>Call this method when uploader params <strong>changed</strong> and send <strong>$event</strong>.</p><pre>&lt;label class=&quot;uploader-circle&quot;&gt;<br>  &lt;i class=&quot;fas fa-plus&quot;&gt;&lt;/i&gt;<br>  &lt;input type=&quot;file&quot; (change)=&quot;onFileSelected($event)&quot; id=&quot;uploader&quot;/&gt;<br>&lt;/label&gt;</pre><p><em>OPTIONAL: If we want that uploader let’s upload only image, we use input attribute</em> <strong>accept</strong>.</p><pre>&lt;input type=&quot;file&quot; (change)=&quot;onFileSelected($event)&quot; accept=&quot;image/*&quot; id=&quot;uploader&quot;/&gt;</pre><p>Send request to server for uploading image.</p><pre><strong>import </strong>{Component} <strong>from </strong>&#39;@angular/core&#39;;<br><strong>import </strong>{HttpClient} <strong>from </strong>&#39;@angular/common/http&#39;;<br><br><br>@Component({<br>  selector: &#39;app-image-uploader&#39;,<br>  templateUrl: &#39;./image-uploader.component.html&#39;,<br>  styleUrls: [&#39;./image-uploader.component.scss&#39;]<br>})<br><strong>export class </strong>ImageUploaderComponent {<br><br>  selectedFile: File = <strong>null</strong>;<br>  <strong>public </strong>image: any;<br><br>  <strong>constructor</strong>(<strong>private </strong>http: HttpClient) {<br>  }<br><br>  <em>/**<br>   * Validate uploader params<br>   * </em><strong><em>@param </em></strong><em>event<br>   */<br>  </em><strong>public </strong>onFileSelected(event) {<br>    <strong>this</strong>.selectedFile = &lt;File&gt;event.target.files[0];<br>    <strong>if </strong>(<strong>this</strong>.selectedFile) {<br>      <strong>return this</strong>.upload();<br>    }<br>  }<br><br><br>  <em>/**<br>   * Upload image to server and receive image object<br>   */<br>  </em>upload() {<br>    <strong>const </strong>fd = <strong>new </strong>FormData();<br>    fd.append(&#39;image&#39;, <strong>this</strong>.selectedFile, <strong>this</strong>.selectedFile.name);<br>    <strong>this</strong>.http.post(&#39;http://example.com/upload/image&#39;, fd).subscribe((res: <strong>any</strong>) =&gt; {<br>      <strong>this</strong>.image = res.data;<br>    }, (err: <strong>any</strong>) =&gt; {<br>        // Show error message or make something.<br>    });<br>  }<br><br>}</pre><p>In our case if it’s alright our request returns us following response:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VC7459ltMDDbIyMSPOIPUw.png" /><figcaption>Request Respond</figcaption></figure><p>The last thing which we need to do, is to return the response to our form. Let’s do it through Angular <strong>Output.</strong> It means that at every time when we upload image we receive response from the server to form.</p><pre><strong>import </strong>{Component, EventEmitter, Output} <strong>from </strong>&#39;@angular/core&#39;;<br><strong>import </strong>{HttpClient} <strong>from </strong>&#39;@angular/common/http&#39;;<br><br><br>@Component({<br>  selector: &#39;app-image-uploader&#39;,<br>  templateUrl: &#39;./image-uploader.component.html&#39;,<br>  styleUrls: [&#39;./image-uploader.component.scss&#39;]<br>})<br><strong>export class </strong>ImageUploaderComponent {<br><br>  selectedFile: File = <strong>null</strong>;<br>  @Output() event = <strong>new </strong>EventEmitter();<br>  <strong>public </strong>image: any;<br><br>  <strong>constructor</strong>(<strong>private </strong>http: HttpClient) {<br>  }<br><br>  <em>/**<br>   *  Validate uploader params<br>   * </em><strong><em>@param </em></strong><em>event<br>   */<br>  </em><strong>public </strong>onFileSelected(event) {<br>    <strong>this</strong>.selectedFile = &lt;File&gt;event.target.files[0];<br>    <strong>if </strong>(<strong>this</strong>.selectedFile) {<br>      <strong>return this</strong>.upload();<br>    }<br>  }<br><br><br>  <em>/**<br>   * Upload image to server and receive image object<br>   */<br>  </em>upload() {<br>    <strong>const </strong>fd = <strong>new </strong>FormData();<br>    fd.append(&#39;image&#39;, <strong>this</strong>.selectedFile, <strong>this</strong>.selectedFile.name);<br>    <strong>this</strong>.http.post(&#39;http://example.com/upload/image&#39;, fd).subscribe((res: <strong>any</strong>) =&gt; {<br>      <strong>this</strong>.image = res.data;<br>      <strong>this</strong>.event.emit(<strong>this</strong>.image);<br>    }, (err: <strong>any</strong>) =&gt; {<br>      // Show error message or make something.<br>    });<br>  }<br><br>}</pre><h3>How we use image uploader</h3><p>When we have a form with image uploader we simply use it.</p><pre>&lt;form&gt;<br>  &lt;input type=&quot;text&quot; placeholder=&quot;Name&quot; /&gt;<br>  &lt;div class=&quot;uploader&quot;&gt;</pre><pre>    &lt;app-image-uploader (event)=&quot;giveImage($event)&quot;&gt;&lt;/app-image-uploader&gt;</pre><pre>  &lt;/div&gt;<br>&lt;/form&gt;</pre><p><em>Nota bene: Image uploader’s parent should have position: relative;</em></p><p>In <strong>giveImage</strong> method we have response from image-uploader..</p><pre>public giveImage(event)<br>{<br>  console.log(event);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gFYa4gQnoodWuSA8qBUECQ.png" /><figcaption>Event console log</figcaption></figure><h3>Final Result</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*eEiTvkbFlA8BSzdHQahBMg.png" /></figure><h3>Conclusion</h3><p>If we create uploader like separate component we can use them in every form which we use. It’s easy to maintain and add new features.</p><p><strong>Thanks for attention, waiting for your feedback.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69dadf3e2728" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>