<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Angular &#8211; Sibeesh Passion</title>
	<atom:link href="https://sibeeshpassion.com/tag/angular/feed/" rel="self" type="application/rss+xml" />
	<link>https://sibeeshpassion.com</link>
	<description>My passion towards life</description>
	<lastBuildDate>Wed, 17 Jul 2019 15:43:23 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>/wp-content/uploads/2017/04/Sibeesh_Passion_Logo_Small.png</url>
	<title>Angular &#8211; Sibeesh Passion</title>
	<link>https://sibeeshpassion.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Publish Your Angular GitHub Repository as a GitHub Page</title>
		<link>https://sibeeshpassion.com/publish-your-angular-github-repository-as-a-github-page/</link>
					<comments>https://sibeeshpassion.com/publish-your-angular-github-repository-as-a-github-page/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Mon, 22 Apr 2019 12:55:38 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[GitHub]]></category>
		<category><![CDATA[GitHub Pages]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=13642</guid>

					<description><![CDATA[[toc] Introduction In this article, we will see how we can publish one of our GitHub repository as a GitHub page. We will be discussing the problems I have faced while doing so, with screenshots. If you are ready, let&#8217;s just go ahead and create the page. Background I am sure that there are many related articles available on internet, but some of them are only explaining the steps to achieve this, but not the problems faced, so I thought I could write about the problems I faced while creating a page for my GitHub repository. Prerequisites A User/Organization GitHub [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>[toc]</p>



<h2 class="wp-block-heading">Introduction </h2>



<p>In this article, we will see how we can publish one of our GitHub repository as a GitHub page. We will be discussing the problems I have faced while doing so, with screenshots. If you are ready, let&#8217;s just go ahead and create the page. </p>



<h2 class="wp-block-heading">Background</h2>



<p>I am sure that there are many related articles available on internet, but some of them are only explaining the steps to achieve this, but not the problems faced, so I thought I could write about the problems I faced while creating a page for my GitHub repository.</p>



<h2 class="wp-block-heading">Prerequisites </h2>



<ol class="wp-block-list"><li>A User/Organization GitHub account</li><li>An Angular repository</li></ol>



<h2 class="wp-block-heading">Publish GitHub Page</h2>



<h3 class="wp-block-heading">Selecting the repository</h3>



<p>In this phase, you can select any Angular repository you have in your profile. I am going to select my repository <a href="https://github.com/SibeeshVenu/Azure-AI-Image-Text-Reader">Azure-AI-Image-Text-Reader</a>.</p>



<h3 class="wp-block-heading">Creating the GitHub page</h3>



<p>Now let&#8217;s build our repository. Please make sure to change the base href property of your index.html file. Usually the value of the base href is &#8220;/&#8221;, now we are going to change the same with the argument  <br><em>&#8211;base-href</em> in our build command. </p>



<pre class="wp-block-code"><code>ng build --prod --base-href "https://sibeeshvenu.com/Azure-AI-Image-Text-Reader/"</code></pre>



<p>I am already using GitHub page for my user account and I have also enabled the custom domain for the same, that is the reason why I had given the custom URL in the base href. In your case, you should provide the URL as https://&lt;username&gt;.github.io/&lt;repositoryName&gt;/</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p> <br>Please do not remove the slash (/) at the last of the URL and also remember that the repository name is case sensitive.  </p><cite>Case sensitive repository URL</cite></blockquote>



<p>The above command will create a new folder if you are using angular cli 6 or the above, the folder name will be the project name specified in the angular.json file.</p>



<pre class="wp-block-code"><code>{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "azure-ai-image-text-reader": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {
        "@schematics/angular:component": {
          "styleext": "scss"
        }
      }
}</code></pre>



<p>With the help of the npm package  angular-cli-ghpages, we can easily upload the build contents to our repository. </p>



<pre class="wp-block-code"><code>npm i angular-cli-ghpages --save-dev</code></pre>



<p>And then use the command below.</p>



<pre class="wp-block-code"><code>npx ngh --dir=dist/Azure-AI-Image-Text-Reader</code></pre>



<p>

If you are not sure about the difference between npm and npx, I recommend you to read my article <a href="https://medium.com/@sibeeshvenu/npm-vs-npx-f737dea2fb4">here</a>.

</p>



<p>Here the &#8211;dir property is used to specify the folder where the build contents are generated. Please be noted that by default the directory name is dist, so if your angular cli version is below 6, you don&#8217;t need to specify the folder name.</p>



<p>If you are getting an error as preceding, while you run the ngh command, please make sure that you had installed the package </p>



<pre class="wp-block-code"><code>PS C:\Users\SibeeshVenu\source\repos\Azure-AI-Image-Text-Reader> npx ngh --dir='dist/azure-ai-image-text-reader' --branch=page
npx: installed 87 in 8.588s
Path must be a string. Received undefined
(node:16984) [DEP0022] DeprecationWarning: os.tmpDir() is deprecated. Use os.tmpdir() instead.</code></pre>



<p>Once the task is done, we can go to our repository settings and activate the GitHub page for our repository. Click on the settings and go to the section GitHub Pages.</p>



<figure class="wp-block-image"><img fetchpriority="high" decoding="async" width="650" height="530" src="https://sibeeshpassion.com/wp-content/uploads/2019/04/GitHub-Page-Settings.png" alt="" class="wp-image-13644" srcset="/wp-content/uploads/2019/04/GitHub-Page-Settings.png 650w, /wp-content/uploads/2019/04/GitHub-Page-Settings-300x245.png 300w, /wp-content/uploads/2019/04/GitHub-Page-Settings-400x326.png 400w" sizes="(max-width: 650px) 100vw, 650px" /><figcaption>GitHub Pages Settings</figcaption></figure>



<p>Now you can go to the page URL and check whether you angular application is loading correctly or not. In my case, I can go to the URL  <br><a href="https://sibeeshvenu.github.io/Azure-AI-Image-Text-Reader/">https://sibeeshvenu.github.io/Azure-AI-Image-Text-Reader/</a>  or  <br><a href="https://sibeeshvenu.github.io/Azure-AI-Image-Text-Reader/">https://sibeeshvenu.com/Azure-AI-Image-Text-Reader/</a> </p>



<h2 class="wp-block-heading">Conclusion</h2>



<p>Wow!. Now we have learned, how we can publish a GitHub page of our GitHub repository. We have also covered possible small mistakes and the remedies for the same.</p>



<h2 class="wp-block-heading">Your turn. What do you think?</h2>



<p>Thanks a lot for reading. Did I miss anything that you may think which is needed in this article? Could you find this post as useful? Kindly do not forget to share me your feedback.</p>



<p>Kindest Regards<br>Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/publish-your-angular-github-repository-as-a-github-page/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Using Azure Cognitive Service Computer Vision AI to read text from an image</title>
		<link>https://sibeeshpassion.com/using-azure-cognitive-service-computer-vision-ai-to-read-text-from-an-image/</link>
					<comments>https://sibeeshpassion.com/using-azure-cognitive-service-computer-vision-ai-to-read-text-from-an-image/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Thu, 04 Apr 2019 07:50:15 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[Azure]]></category>
		<category><![CDATA[Cognitive Services]]></category>
		<category><![CDATA[AI]]></category>
		<category><![CDATA[Azure AI]]></category>
		<category><![CDATA[Azure Cognitive Services]]></category>
		<category><![CDATA[Computer Vision]]></category>
		<category><![CDATA[Image to Text]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=13604</guid>

					<description><![CDATA[[toc] Introduction The Microsoft Azure has a lot to offer when it comes to Cognitive Services, trying out them is really fun. Here in this article, we are going to see how we can detect and read texts from an image and show it in the display using the Cognitive Service Computer Vision AI. The service Computer Vision has it&#8217;s own machine language running which helps us to do our task in an easy and effective manner. It uses the technology Optical Character Recognition and extracts the words or text to a readable format. All we have to do is, [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>[toc]</p>



<h2 class="wp-block-heading">Introduction</h2>



<p>The Microsoft Azure has a lot to offer when it comes to Cognitive Services, trying out them is really fun. Here in this article, we are going to see how we can detect and read texts from an image and show it in the display using the Cognitive Service Computer Vision AI. The service Computer Vision has it&#8217;s own machine language running which helps us to do our task in an easy and effective manner. It uses the technology Optical Character Recognition and extracts the words or text to a readable format. All we have to do is, using the service and write some custom codes as per our requirement. Sounds good?  If yes, let&#8217;s just skip the introduction and jump on to the real fun. </p>



<h2 class="wp-block-heading">Background</h2>



<p>I love quotes, and I strongly believe that a single quote can do an impact in your life sometimes. One of my hobbies is collecting the images which contain quotes in it. Now, with the help of Azure Computer Vision cognitive service, I thought of creating an application which can get the quotes from the image and save it. You can easily think of many other usages of this service, below are some of them.</p>



<ol class="wp-block-list"><li>Using the translator, which scan the image, read the text and translate</li><li>Document creation from the images, which will be useful to save hours</li><li>A Google Glass, which capture what you see and translate the content to your native language</li><li>A digital medical prescription from the actual one</li></ol>



<p>Imagine that you need to create a solution which can save all of your medical prescription contents in a table in a database, so that you can easily sort/filter and show them in a UI. You can even create a mobile application to do that. The possibilities are countless. Now let&#8217;s build one of them.</p>



<h2 class="wp-block-heading">Prerequisites</h2>



<p>Before we start, we should have the following things in our hand. </p>



<ol class="wp-block-list"><li>A valid Azure Subscription </li><li>A good Code editor, I prefer VSCode or Visual Studio</li></ol>



<h2 class="wp-block-heading">Source Code</h2>



<p>The source code be downloaded from <a href="https://github.com/SibeeshVenu/Azure-AI-Image-Text-Reader">here</a>.</p>



<h2 class="wp-block-heading">Let Us Start</h2>



<p>As I mentioned earlier, we will be using an Azure service to build our application. Azure is a cloud computing service created by Microsoft, for the last few years there are significant growth in Azure. The services provided in Azure can be found <a href="https://docs.microsoft.com/en-us/azure/index#pivot=products&amp;panel=all">here</a>. </p>



<h3 class="wp-block-heading">Create the Computer Vision Resource in Azure</h3>



<p>To create the Azure resource, login to the Azure portal and click on the +Create a resource menu. Once the window loads, you can search for the resource Computer Vision as shown in the preceding image.</p>



<figure class="wp-block-image"><img decoding="async" width="651" height="224" src="https://sibeeshpassion.com/wp-content/uploads/2019/02/Computer-Vision-Azure-Resource.png" alt="" class="wp-image-13606" srcset="/wp-content/uploads/2019/02/Computer-Vision-Azure-Resource.png 651w, /wp-content/uploads/2019/02/Computer-Vision-Azure-Resource-300x103.png 300w, /wp-content/uploads/2019/02/Computer-Vision-Azure-Resource-400x138.png 400w" sizes="(max-width: 651px) 100vw, 651px" /><figcaption>Computer Vision Azure Resource</figcaption></figure>



<p>Now, click on the create button and fill the form.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" width="299" height="355" src="https://sibeeshpassion.com/wp-content/uploads/2019/02/Create-Resource.png" alt="" class="wp-image-13607" srcset="/wp-content/uploads/2019/02/Create-Resource.png 299w, /wp-content/uploads/2019/02/Create-Resource-253x300.png 253w" sizes="(max-width: 299px) 100vw, 299px" /><figcaption>Create Resource</figcaption></figure></div>



<p>It may take a few minutes to finish the development of the resource. Once it is finished, we can go to the resource and get our keys from the Keys section under Resource Management. Save those keys somewhere as we need them while we create our applications.</p>



<h3 class="wp-block-heading">Develop the Angular Client Application</h3>



<p>Here, we will be creating an Angular application with the help of Angular CLI and to create the application we are going to use the command <em>ng new Azure-AI-Image-Text-Reader</em> where the last parameter is our application name. You should also be given a chance to select your CSS and routing option. Please be noted that you can add them later as well. </p>



<p>Once the application is ready, we can create our own Angular service. </p>



<h4 class="wp-block-heading">detection.service.ts</h4>



<p>To create the service, let&#8217;s use the preceding command.</p>



<script src="https://gist.github.com/SibeeshVenu/d0dc3b759e2b124adc710562a07b39ae.js"></script>



<p>Here the name &#8216;detection&#8217; is our service name. Now we can edit the service code as preceding.</p>



<script src="https://gist.github.com/SibeeshVenu/70bee412d05aa30f9c000c6aec7ee17d.js"></script>



<p>As you can see that we are creating an HttpClient call to our baseUrl which is been configured in our config.ts file. To call the Computer Vision AI service, it is mandatory to pass the subscription key, the one we have created in the Azure portal, to the request by using the header Ocp-Apim-Subscription-Key. </p>



<h4 class="wp-block-heading">config.ts</h4>



<script src="https://gist.github.com/SibeeshVenu/378bc41c350e21ba7e9c52a78dbbe086.js"></script>



<p>Please remember to change the baseUrl and apiKey before you run the application.</p>



<h4 class="wp-block-heading">home.component.ts</h4>



<p>As our service is ready, let&#8217;s create our component now using the command below.</p>



<script src="https://gist.github.com/SibeeshVenu/fa5b288459ff0219a4da636b4406dc1d.js"></script>



<p>Once the component is created, let&#8217;s go to the file home.component.ts and edit our code.</p>



<script src="https://gist.github.com/SibeeshVenu/5d80e48e599b406348e2a9c08fdefbcc.js"></script>



<p>Once the component is loaded in the screen, the user will be able to type or paste the URL of an image and submit the same. Before submitting the request, we are validating the input using the FormControl, we are using the required validator and pattern validator which uses to find whether the given url is valid or not. Once the request is been made we are calling our detection service with a post request and once we get the result from the Azure service, we are looping through the result and formatting the data accordingly.  </p>



<h4 class="wp-block-heading">home.component.html</h4>



<p>As we have our component logic ready in hand, now it is time to edit our component template. Let&#8217;s edit our home.component.html file as follows.</p>



<script src="https://gist.github.com/SibeeshVenu/3758ad77c5164deb3eee3bcbaa8cbaf0.js"></script>



<p>We use Angular Material design to develop our Angular application, the material component mat-card is a card component which can act as a container, apart from the mat-card we are using the components mat-form-field, matInput, mat-error, mat-card-image in our home component. You can use the command <em>npm install &#8211;save @angular/material @angular/cdk @angular/animations</em> to install the material in your application.</p>



<p>Once the component loads, we are giving an option to submit a valid image URL, if the URL provided is not valid, we are disabling the submit button. Once the user submit the request, then we are calling our detection service. Sounds good?</p>



<h2 class="wp-block-heading">Output</h2>



<p>Below are the screen print of our application.</p>



<figure class="wp-block-image"><img decoding="async" width="1024" height="389" src="https://sibeeshpassion.com/wp-content/uploads/2019/02/Start-Screen-1024x389.png" alt="" class="wp-image-13609" srcset="/wp-content/uploads/2019/02/Start-Screen-1024x389.png 1024w, /wp-content/uploads/2019/02/Start-Screen-300x114.png 300w, /wp-content/uploads/2019/02/Start-Screen-768x291.png 768w, /wp-content/uploads/2019/02/Start-Screen-400x152.png 400w, /wp-content/uploads/2019/02/Start-Screen.png 1228w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>Now we can test this application by giving the URL of the below image.</p>



<figure class="wp-block-image"><img decoding="async" width="741" height="118" src="https://sibeeshpassion.com/wp-content/uploads/2019/02/quote.png" alt="" class="wp-image-13610" srcset="/wp-content/uploads/2019/02/quote.png 741w, /wp-content/uploads/2019/02/quote-300x48.png 300w, /wp-content/uploads/2019/02/quote-400x64.png 400w" sizes="(max-width: 741px) 100vw, 741px" /></figure>



<p>Once you submit the URL, you should be able to see an output as below.</p>



<figure class="wp-block-image"><img decoding="async" width="650" height="342" src="https://sibeeshpassion.com/wp-content/uploads/2019/02/Result-with-Image-and-Text.png" alt="" class="wp-image-13611" srcset="/wp-content/uploads/2019/02/Result-with-Image-and-Text.png 650w, /wp-content/uploads/2019/02/Result-with-Image-and-Text-300x158.png 300w, /wp-content/uploads/2019/02/Result-with-Image-and-Text-600x315.png 600w, /wp-content/uploads/2019/02/Result-with-Image-and-Text-400x210.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></figure>



<h2 class="wp-block-heading">Demo</h2>



<p>The application demo can be viewed <a href="https://sibeeshvenu.com/Azure-AI-Image-Text-Reader/">here</a>.</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p>Wow!. Now we have learned, what is Azure Computer Vision AI and how to create Azure Computer Vision Cognitive Service. We also learned to create an Angular application which reads the text from images. I hope you found this article useful. I can&#8217;t wait to see what you are going to build with Azure Computer Vision AI. You can also check out the other options we have in Microsoft Azure Computer Vision AI <a href="https://azure.microsoft.com/en-us/services/cognitive-services/computer-vision/">here</a>, I am sure you will love playing with it. </p>



<h2 class="wp-block-heading">Your turn. What do you think?</h2>



<p>Thanks a lot for reading. Did I miss anything that you may think which is needed in this article? Could you find this post as useful? Kindly do not forget to share me your feedback.</p>



<p>Kindest Regards<br>Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/using-azure-cognitive-service-computer-vision-ai-to-read-text-from-an-image/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Deploy Angular App Using Azure DevOps Build and Release Pipelines</title>
		<link>https://sibeeshpassion.com/deploy-angular-app-using-azure-devops-build-and-release-pipelines/</link>
					<comments>https://sibeeshpassion.com/deploy-angular-app-using-azure-devops-build-and-release-pipelines/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Mon, 07 Jan 2019 15:59:50 +0000</pubDate>
				<category><![CDATA[Azure]]></category>
		<category><![CDATA[Angular]]></category>
		<category><![CDATA[Angular Pipeline in Azure]]></category>
		<category><![CDATA[Angular Release Pipeline]]></category>
		<category><![CDATA[Azure DevOps]]></category>
		<category><![CDATA[Deploy Angular to Azure Easily]]></category>
		<category><![CDATA[TFS]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=13530</guid>

					<description><![CDATA[[toc] Introduction I understand that there are many article on the same topic. But most of the solutions didn&#8217;t work for me with the latest pipeline configuration, so, I thought of writing this article. Here, we are going to set up our Build and Release pipeline configuration of our Angular application very easy, in fact, by following some basic tasks. We will be using Azure DevOps FTP pipeline service connection for the configuration. Let&#8217;s stop the introduction and jump in to the configuration. Background I was trying to deploy my Angular application to Azure, for that I wanted to set [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>[toc]</p>



<h2 class="wp-block-heading">Introduction</h2>



<p>I understand that there are many article on the same topic. But most of the solutions didn&#8217;t work for me with the latest pipeline configuration, so, I thought of writing this article. Here, we are going to set up our Build and Release pipeline configuration of our Angular application very easy, in fact, by following some basic tasks. We will be using Azure DevOps FTP pipeline service connection for the configuration. Let&#8217;s stop the introduction and jump in to the configuration. </p>



<h2 class="wp-block-heading">Background</h2>



<p>I was trying to deploy my <a href="https://sibeeshpassion.com/category/angular">Angular</a> application to Azure, for that I wanted to set up my build and release pipelines. I had followed some tutorials which are available already, but I was facing some issues with the same. Later, I had decided to use the Azure FTP Upload Release Task. So, basically, we will be having only one task in our Release pipeline.</p>



<h2 class="wp-block-heading">Set Up the Pipelines</h2>



<p>As I was mentioning, here, we are going to configure our Build and Release configuration. </p>



<h3 class="wp-block-heading">Build Pipeline</h3>



<p>Here we are going to configure the Azure DevOps build pipeline. But, before, we need to define our script in the package.json file. </p>



<script src="https://gist.github.com/nanotroy/6300ed763b7a9c508545b08cddd194cc.js"></script>



<p>If you have different routes, and if you need to access them directly in the URL of the browser, you should consider adding a web.config file in your src folder. </p>



<script src="https://gist.github.com/nanotroy/48ef50c3d524c3ac65e3a23fed235bd7.js"></script>



<p>Once that is done, add it as an asset in the angular.json file.</p>



<script src="https://gist.github.com/nanotroy/7cd6f89662554f217896239194b51310.js"></script>



<p>Now, go to your Azure DevOps site, and click on Pipelines and then Builds. Click on the plus icon.</p>



<h4 class="wp-block-heading">Pipeline</h4>



<p>Click on the Pipeline section. Here you can mention your pipeline name and the Agent pool, please remember to select the Agent pool as Hosted VS2017, or else you may end up seeing an error as &#8220;<a href="https://stackoverflow.com/questions/51227020/npm-failed-with-return-code-4294963238-in-ci-in-vsts/54072646#54072646">Npm failed with return code: 1 2019-01-07T10:14:37.3309955Z ##[section]Finishing: npm build</a>&#8220;.</p>



<figure class="wp-block-image"><img decoding="async" width="650" height="304" src="https://sibeeshpassion.com/wp-content/uploads/2019/01/Select-the-Pipeline-Agent.jpg" alt="" class="wp-image-13531" srcset="/wp-content/uploads/2019/01/Select-the-Pipeline-Agent.jpg 650w, /wp-content/uploads/2019/01/Select-the-Pipeline-Agent-300x140.jpg 300w, /wp-content/uploads/2019/01/Select-the-Pipeline-Agent-400x187.jpg 400w" sizes="(max-width: 650px) 100vw, 650px" /><figcaption>Select the Pipeline Agent</figcaption></figure>



<h4 class="wp-block-heading">Phase 1</h4>



<p>I recommend you to leave this as it is, you can change the display name though. </p>



<h4 class="wp-block-heading">npm install</h4>



<p>Click on the + icon in the Phase section and search for &#8220;npm&#8221; and click add. Now we can configure this task. </p>



<figure class="wp-block-image"><img decoding="async" width="650" height="493" src="https://sibeeshpassion.com/wp-content/uploads/2019/01/npm-install-task.jpg" alt="" class="wp-image-13532" srcset="/wp-content/uploads/2019/01/npm-install-task.jpg 650w, /wp-content/uploads/2019/01/npm-install-task-300x228.jpg 300w, /wp-content/uploads/2019/01/npm-install-task-400x303.jpg 400w" sizes="(max-width: 650px) 100vw, 650px" /><figcaption>npm install task</figcaption></figure>



<p>You can also click on the ribbon View YAML, to see the <g class="gr_ gr_3 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling" id="3" data-gr-id="3">yml</g> version of the task.</p>



<h4 class="wp-block-heading">npm build</h4>



<p>In this step, we will add a new npm task and configure it for our build script. </p>



<figure class="wp-block-image"><img decoding="async" width="650" height="513" src="https://sibeeshpassion.com/wp-content/uploads/2019/01/npm-run-build.jpg" alt="" class="wp-image-13533" srcset="/wp-content/uploads/2019/01/npm-run-build.jpg 650w, /wp-content/uploads/2019/01/npm-run-build-300x237.jpg 300w, /wp-content/uploads/2019/01/npm-run-build-400x316.jpg 400w" sizes="(max-width: 650px) 100vw, 650px" /><figcaption>npm run build</figcaption></figure>



<p>Please be noted that the command is custom and we have given the script which we have already set in our package.json file, which is prod-build-dev. </p>



<h4 class="wp-block-heading">Publish Artifact</h4>



<p>Here, in this step, we will publish our artifacts generated. This is very important, otherwise, the release configuration will not be able to find your package.json file in the directory. Add a new task called &#8220;Publish Build Artifacts&#8221; and configure the same as mentioned in the image below. </p>



<figure class="wp-block-image"><img decoding="async" width="650" height="486" src="https://sibeeshpassion.com/wp-content/uploads/2019/01/Publish-Build-Artifacts.jpg" alt="" class="wp-image-13534" srcset="/wp-content/uploads/2019/01/Publish-Build-Artifacts.jpg 650w, /wp-content/uploads/2019/01/Publish-Build-Artifacts-300x224.jpg 300w, /wp-content/uploads/2019/01/Publish-Build-Artifacts-400x299.jpg 400w" sizes="(max-width: 650px) 100vw, 650px" /><figcaption>Publish Build Artifacts<br></figcaption></figure>



<h4 class="wp-block-heading">Enable the Continuous Integration</h4>



<p>As we have set up the Tasks, now it is time to set up the continuous integration. Click on the Triggers section and check the Enable continuous integration.  </p>



<figure class="wp-block-image"><img decoding="async" width="650" height="216" src="https://sibeeshpassion.com/wp-content/uploads/2019/01/Enable-Continuous-Integration.jpg" alt="" class="wp-image-13535" srcset="/wp-content/uploads/2019/01/Enable-Continuous-Integration.jpg 650w, /wp-content/uploads/2019/01/Enable-Continuous-Integration-300x100.jpg 300w, /wp-content/uploads/2019/01/Enable-Continuous-Integration-400x133.jpg 400w" sizes="(max-width: 650px) 100vw, 650px" /><figcaption>Enable Continuous Integration</figcaption></figure>



<h4 class="wp-block-heading">Debugging the Build</h4>



<p>If you ever need to debug the build pipeline, you can enable the same in the Variable section. Just making the system.debug value to true will do the trick. </p>



<figure class="wp-block-image"><img decoding="async" width="651" height="137" src="https://sibeeshpassion.com/wp-content/uploads/2019/01/Debugging-Build.jpg" alt="" class="wp-image-13536" srcset="/wp-content/uploads/2019/01/Debugging-Build.jpg 651w, /wp-content/uploads/2019/01/Debugging-Build-300x63.jpg 300w, /wp-content/uploads/2019/01/Debugging-Build-400x84.jpg 400w" sizes="(max-width: 651px) 100vw, 651px" /><figcaption>Debugging Build</figcaption></figure>



<h4 class="wp-block-heading">Run the Build</h4>



<p>Once you are done everything, you can click on the Save &amp; Queue button to initiate the build. Our Agent will run now, the tasks will be executed, as we have enabled the debug property to true in the Variables, we can now see the detailed logs in the console. The following tasks will be happening.</p>



<figure class="wp-block-image"><img decoding="async" width="641" height="1008" src="https://sibeeshpassion.com/wp-content/uploads/2019/01/Build-Pipeline-Output.jpg" alt="" class="wp-image-13537" srcset="/wp-content/uploads/2019/01/Build-Pipeline-Output.jpg 641w, /wp-content/uploads/2019/01/Build-Pipeline-Output-191x300.jpg 191w, /wp-content/uploads/2019/01/Build-Pipeline-Output-400x629.jpg 400w, /wp-content/uploads/2019/01/Build-Pipeline-Output-382x600.jpg 382w" sizes="(max-width: 641px) 100vw, 641px" /><figcaption>Build Pipeline Output</figcaption></figure>



<h3 class="wp-block-heading">Release Pipeline</h3>



<p>Wow, we have successfully created our build pipeline, now it is time to create a Release pipeline. As I mentioned earlier, we are going to have only one Task in our Release pipeline, which is nothing but &#8220;FTP Upload&#8221;. Click on the Pipelines and then Releases, click on the +New icon to create a new Release pipeline. </p>



<h4 class="wp-block-heading">Select the Artifacts</h4>



<p>Here, in this step, we should select the Artifacts generated in the build.</p>



<figure class="wp-block-image"><img decoding="async" width="650" height="563" src="https://sibeeshpassion.com/wp-content/uploads/2019/01/Select-the-Artifacts.jpg" alt="" class="wp-image-13539" srcset="/wp-content/uploads/2019/01/Select-the-Artifacts.jpg 650w, /wp-content/uploads/2019/01/Select-the-Artifacts-300x260.jpg 300w, /wp-content/uploads/2019/01/Select-the-Artifacts-400x346.jpg 400w" sizes="(max-width: 650px) 100vw, 650px" /><figcaption>Select the Artifacts</figcaption></figure>



<h4 class="wp-block-heading">Select the Stage</h4>



<p>Click on the Stages and add one.</p>



<h4 class="wp-block-heading">Adding a FTP Service Connection</h4>



<p>Before we add a new FTP Upload task, we need to create a new FTP service connection in our Azure DevOps site. Click on the Project Settings on the bottom left corner, go to the Pipelines section, and then click on the Service connections. Now click on the + New service connection, in the pop up you need to provide the details which you can get from the Publish profile of your Azure Web App (Click on the Get Publish Profile in your Web App resource, overview section in the Azure portal).</p>



<figure class="wp-block-image"><img decoding="async" width="649" height="370" src="https://sibeeshpassion.com/wp-content/uploads/2019/01/Add-a-Generic-Service-Connection.jpg" alt="" class="wp-image-13540" srcset="/wp-content/uploads/2019/01/Add-a-Generic-Service-Connection.jpg 649w, /wp-content/uploads/2019/01/Add-a-Generic-Service-Connection-300x171.jpg 300w, /wp-content/uploads/2019/01/Add-a-Generic-Service-Connection-400x228.jpg 400w" sizes="(max-width: 649px) 100vw, 649px" /><figcaption>Add a Generic Service Connection</figcaption></figure>



<h4 class="wp-block-heading">Add the FTP Upload Task</h4>



<p>Now it is time to add the FTP Upload Task. Click on the + icon in the Agent Job Task and add the task FTP Upload.</p>



<figure class="wp-block-image"><img decoding="async" width="470" height="807" src="https://sibeeshpassion.com/wp-content/uploads/2019/01/FTP-Upload-Task.jpg" alt="" class="wp-image-13541" srcset="/wp-content/uploads/2019/01/FTP-Upload-Task.jpg 470w, /wp-content/uploads/2019/01/FTP-Upload-Task-175x300.jpg 175w, /wp-content/uploads/2019/01/FTP-Upload-Task-400x687.jpg 400w, /wp-content/uploads/2019/01/FTP-Upload-Task-349x600.jpg 349w" sizes="(max-width: 470px) 100vw, 470px" /><figcaption>FTP Upload Task</figcaption></figure>



<p>Here the remote directory is the folder where our application files are going to be, you should be able to see those files if you just log in to the explorer using your FTP details from your app publish profile. </p>



<h4 class="wp-block-heading">Create a Release</h4>



<p>Now, it is time to create a Release, click on the + Release button and then + Create a release. In the upcoming window, you should be able to see the pipeline and the Artifacts selected. Just click on the Create button. The Agent will be started in a few seconds, once it is ready, it will execute the tasks. Please be noted that the FTP Upload task will remove the content from the directory first and then upload the new one. </p>



<figure class="wp-block-image"><img decoding="async" width="598" height="247" src="https://sibeeshpassion.com/wp-content/uploads/2019/01/Release-Pipeline-Tasks-Output.jpg" alt="" class="wp-image-13543" srcset="/wp-content/uploads/2019/01/Release-Pipeline-Tasks-Output.jpg 598w, /wp-content/uploads/2019/01/Release-Pipeline-Tasks-Output-300x124.jpg 300w, /wp-content/uploads/2019/01/Release-Pipeline-Tasks-Output-400x165.jpg 400w" sizes="(max-width: 598px) 100vw, 598px" /><figcaption>Release Pipeline Tasks Output</figcaption></figure>



<h2 class="wp-block-heading">Change the App Service Virtual Path</h2>



<p>As we have given a custom folder in the Release configuration, we should also change the Virtual Path of the Azure App service. To do so, go to your Azure App Service and then select Virtual Path under Application Settings. Set the Virtual Path as &#8220;/&#8221; and Virtual Path as &#8220;site\wwwroot\wwwroot\yourappname(the folder name inside dist folder)&#8221; and the type as &#8220;Application&#8221;.</p>



<figure class="wp-block-image"><img decoding="async" width="653" height="94" src="https://sibeeshpassion.com/wp-content/uploads/2019/01/Set-Virtual-Physical-Path.jpg" alt="" class="wp-image-13544" srcset="/wp-content/uploads/2019/01/Set-Virtual-Physical-Path.jpg 653w, /wp-content/uploads/2019/01/Set-Virtual-Physical-Path-300x43.jpg 300w, /wp-content/uploads/2019/01/Set-Virtual-Physical-Path-400x58.jpg 400w" sizes="(max-width: 653px) 100vw, 653px" /><figcaption>Set Virtual Physical Path</figcaption></figure>



<p>Once you are done, you can see your Angular application running. </p>



<h2 class="wp-block-heading">Conclusion</h2>



<p>Wow!. Now we have learned,</p>



<ul class="wp-block-list"><li>How to set up the Azure DevOps Build Pipeline configuration</li><li> How to set up the Azure DevOps Release Pipeline configuration </li><li>How to create new FTP Service Connection in Azure DevOps</li><li>How to configure Azure Web App</li></ul>



<p>You can always read my articles related to Azure <a href="https://sibeeshpassion.com/category/azure">here</a>. </p>



<h2 class="wp-block-heading">Your turn. What do you think?</h2>



<p>Thanks a lot for reading. Did I miss anything that you may think which is needed in this article? Could you find this post as useful? Kindly do not forget to share me your feedback.</p>



<p>Kindest Regards<br>Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/deploy-angular-app-using-azure-devops-build-and-release-pipelines/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Create Your Own NPM Package &#8211; Private or Public</title>
		<link>https://sibeeshpassion.com/create-your-own-npm-package-private-or-public/</link>
					<comments>https://sibeeshpassion.com/create-your-own-npm-package-private-or-public/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Mon, 05 Nov 2018 21:36:57 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[create your own npm package]]></category>
		<category><![CDATA[custom package angular]]></category>
		<category><![CDATA[NPM]]></category>
		<category><![CDATA[npm package]]></category>
		<category><![CDATA[publish npm package]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=13326</guid>

					<description><![CDATA[[toc] Introduction Wow, you are going to create your own package? Either a private one or a public one? You were looking for a documentation on how to create your own package in NPM, and you ended up landing here? No, worries, in this post I will help you with that. At the end of this article, you will get to know how can you create your own package in the NPM registry. Enough talking, let&#8217;s jump into the coding. I hope you will find this post useful. Source Code The source code can be found here. Background Sometimes creating your [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h2>Introduction</h2>
<p>Wow, you are going to create your own package? Either a private one or a public one? You were looking for a documentation on how to create your own package in NPM, and you ended up landing here? No, worries, in this post I will help you with that. At the end of this article, you will get to know how can you create your own package in the NPM registry. Enough talking, let&#8217;s jump into the coding. I hope you will find this post useful.</p>
<h2>Source Code</h2>
<p>The source code can be found <a href="https://github.com/SibeeshVenu/Your-Own-Npm-Package">here</a>.</p>
<h2>Background</h2>
<p>Sometimes creating your own packages will be essential especially when you work with some big companies/clients where they can reuse their components/packages. Doesn&#8217;t it really make sense? As a developer, it is our job to give that option to our client. In this article, I will be creating</p>
<ul>
<li>an <a href="https://sibeeshpassion.com/category/angular/">Angular</a> application</li>
<li>the build and publish the angular application to the NPM registry</li>
<li>another application, where we can use the NPM package which we have created</li>
</ul>
<p>Before you start with, please make sure that you have an account in npmjs, so that you can publish your package there. You can always have a private space in NPM registry, but you must pay for that service, hence in this article, I will walk you through how we can publish your packages to publically, however the steps are going to be same for Private as well.</p>
<h2>Creating your Angular application</h2>
<p>The first thing we are going to do is to create an application and I will name this org-npm-package.</p>
<h3>Installing Angular CLI</h3>
<p>Yes, as you guessed, we are using Angular CLI. If you haven&#8217;t installed Angular CLI, I recommend you to install the same. It is a great CLI tool for Angular, I am sure you will love that. You can do that by running the below command.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">npm install -g @angular/cli</pre>
<p>Once we set up this project we will be using the Angular CLI commands and you can check Angular CLI documentation for understanding the things you can do with the CLI.</p>
<h3>Generating a new project</h3>
<p>Now it is time to generate our new project. We can use the below command for the same.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">ng new org-npm-package</pre>
<p>And you will be able to see all the hard work this CLI is doing for us. Now that we have created our application, let&#8217;s run our application and see if it is working or not.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">ng serve --open (if you need to open the browser by the app)
ng serve (if you want to manually open the browser).
You can always use 'ng s' as well
</pre>
<p><span style="font-size: 14px;">The command will build your application and run it in the browser.</span></p>
<p>As we develop we will be using the Angular material for the design and we can install it now itself along with the animation and cdk. With the Angular 6+ versions you can also do this by following the below command.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">ng add @angular/material</pre>
<h3>Generate menu module and ng-private-menu component</h3>
<p>Now we have an application to work with and let&#8217;s create a module called Menu and a component ng-private-menu now.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">ng g m modules/menu
ng g c modules/ng-private-menu</pre>
<p>The above command will generate all the files you need to work with. I am going to edit only the HTML of the ng-private-menu component for myself and not going to add any logic. You can add anything you wish.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;div&gt;
  &lt;button mat-button [matMenuTriggerFor]="animals"&gt;Animal index&lt;/button&gt;

  &lt;mat-menu #animals="matMenu"&gt;
    &lt;button mat-menu-item [matMenuTriggerFor]="vertebrates"&gt;Vertebrates&lt;/button&gt;
    &lt;button mat-menu-item [matMenuTriggerFor]="invertebrates"&gt;Invertebrates&lt;/button&gt;
  &lt;/mat-menu&gt;

  &lt;mat-menu #vertebrates="matMenu"&gt;
    &lt;button mat-menu-item [matMenuTriggerFor]="fish"&gt;Fishes&lt;/button&gt;
    &lt;button mat-menu-item [matMenuTriggerFor]="amphibians"&gt;Amphibians&lt;/button&gt;
    &lt;button mat-menu-item [matMenuTriggerFor]="reptiles"&gt;Reptiles&lt;/button&gt;
    &lt;button mat-menu-item&gt;Birds&lt;/button&gt;
    &lt;button mat-menu-item&gt;Mammals&lt;/button&gt;
  &lt;/mat-menu&gt;

  &lt;mat-menu #invertebrates="matMenu"&gt;
    &lt;button mat-menu-item&gt;Insects&lt;/button&gt;
    &lt;button mat-menu-item&gt;Molluscs&lt;/button&gt;
    &lt;button mat-menu-item&gt;Crustaceans&lt;/button&gt;
    &lt;button mat-menu-item&gt;Corals&lt;/button&gt;
    &lt;button mat-menu-item&gt;Arachnids&lt;/button&gt;
    &lt;button mat-menu-item&gt;Velvet worms&lt;/button&gt;
    &lt;button mat-menu-item&gt;Horseshoe crabs&lt;/button&gt;
  &lt;/mat-menu&gt;

  &lt;mat-menu #fish="matMenu"&gt;
    &lt;button mat-menu-item&gt;Baikal oilfish&lt;/button&gt;
    &lt;button mat-menu-item&gt;Bala shark&lt;/button&gt;
    &lt;button mat-menu-item&gt;Ballan wrasse&lt;/button&gt;
    &lt;button mat-menu-item&gt;Bamboo shark&lt;/button&gt;
    &lt;button mat-menu-item&gt;Banded killifish&lt;/button&gt;
  &lt;/mat-menu&gt;

  &lt;mat-menu #amphibians="matMenu"&gt;
    &lt;button mat-menu-item&gt;Sonoran desert toad&lt;/button&gt;
    &lt;button mat-menu-item&gt;Western toad&lt;/button&gt;
    &lt;button mat-menu-item&gt;Arroyo toad&lt;/button&gt;
    &lt;button mat-menu-item&gt;Yosemite toad&lt;/button&gt;
  &lt;/mat-menu&gt;

  &lt;mat-menu #reptiles="matMenu"&gt;
    &lt;button mat-menu-item&gt;Banded Day Gecko&lt;/button&gt;
    &lt;button mat-menu-item&gt;Banded Gila Monster&lt;/button&gt;
    &lt;button mat-menu-item&gt;Black Tree Monitor&lt;/button&gt;
    &lt;button mat-menu-item&gt;Blue Spiny Lizard&lt;/button&gt;
    &lt;button mat-menu-item disabled&gt;Velociraptor&lt;/button&gt;
  &lt;/mat-menu&gt;
&lt;/div&gt;</pre>
<p>Once you have added that HTML, you should import some modules to your menu.module.ts file.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NgPrivateMenuComponent } from '../ng-private-menu/ng-private-menu.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatMenuModule, MatButtonModule } from '@angular/material';


@NgModule({
  declarations: [
    NgPrivateMenuComponent
  ],
  imports: [
    BrowserAnimationsModule,
    CommonModule,
    MatMenuModule,
    MatButtonModule
  ],
  exports: [
    NgPrivateMenuComponent
  ]
})
export class MenuModule { }</pre>
<h3>Set up app.module.ts</h3>
<p>Now it is time to set our App Module. Every Angular app will be having at least one NgModule class <code>AppModule</code>resides in <code>app.module.ts</code>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { MenuModule } from './modules/menu/menu.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    MenuModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</pre>
<div>
<h4>Run your application</h4>
<p>Once you have done everything, you will be able to run &#8220;ng serve&#8221; and see your application working in the browser.</p>
<p><div id="attachment_13327" style="width: 447px" class="wp-caption aligncenter"><a href="https://sibeeshpassion.com/wp-content/uploads/2018/11/Angular-application-output.png"><img decoding="async" aria-describedby="caption-attachment-13327" class="size-full wp-image-13327" src="https://sibeeshpassion.com/wp-content/uploads/2018/11/Angular-application-output.png" alt="Angular application output" width="437" height="314" srcset="/wp-content/uploads/2018/11/Angular-application-output.png 437w, /wp-content/uploads/2018/11/Angular-application-output-300x216.png 300w, /wp-content/uploads/2018/11/Angular-application-output-400x287.png 400w" sizes="(max-width: 437px) 100vw, 437px" /></a><p id="caption-attachment-13327" class="wp-caption-text">Angular application output</p></div></p>
</div>
<h2>Creating the NPM package</h2>
<p>Whenever we do something, it is always a good idea to check whether something is already there or not, to help our development easier. That&#8217;s the advantage of using NPM public registry, we can always search for public repositories or packages which will definitely help in our development process. We have such packages in this case as well, so we are going to use the package called &#8220;ng-packagr&#8221;.</p>
<p>According to the package documentation, the packagr is a tool which transpile your libraries to Angular package format. It is a great package which does its job very well. I would like to give a huge round of applause to the developers/collaborators of that package. Please feel free to see the documentation of that package. You can install the same by running the command below.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">npm i ng-packagr</pre>
<h3>Setting up the package.json</h3>
<p>The first thing we are going to do is, to set the package.json as per the requirement of the packagr. Please add the preceding code to your package.json file.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">"$schema": "./node_modules/ng-packagr/package.schema.json",
  "name": "@sibeeshpassion/org-npm-package",
  "version": "2.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "packagr": "ng-packagr -p package.json"
  },
  "ngPackage": {
    "lib": {
      "entryFile": "public_api.ts"
    },
    "whitelistedNonPeerDependencies": [
      "@angular/animations",
      "@angular/cdk",
      "@angular/common",
      "@angular/compiler",
      "@angular/forms",
      "@angular/core",
      "@angular/http",
      "@angular/material",
      "@angular/platform-browser",
      "@angular/platform-browser-dynamic",
      "@angular/router",
      "core-js",
      "rxjs",
      "tsickle",
      "zone.js"
    ]
  }</pre>
<p>The<strong> $schema </strong>is for making the editing easier and it will add the JSON editing support, especially if you are using the IDE VSCode.</p>
<p>The <strong>name</strong> is the name of your package. And it is a scoped name here. Did you notice that I have used @ before the SibeeshPassion? A scoped name should be started with @ and should be followed by a slash (/). It is a way of grouping all of your packages together in a common place. Doesn&#8217;t it make sense to have all of your company packages under your company name? It has some other benefits as well.</p>
<ol>
<li>You can get unique names for your package, as you will be the only one who can add a package to that group</li>
<li>To install such packages, you need to use @your-org-name/your-package-name</li>
</ol>
<p>You can always read more on the same topic <a href="https://docs.npmjs.com/misc/scope">here</a>.</p>
<p>The <strong>script packagr </strong>is a custom script so that you can just run &#8220;npm run packagr&#8221; and everything else will be done in the background.</p>
<p>The <strong>ngPackage </strong>is the main settings for the packagr package, as it sets the entry point for our packaging. The file public_api.ts should be placed with the same directory of the package.json file. In our case, the public_api.ts contents will be as below.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">export * from './src/app/modules/menu/menu.module';
</pre>
<p>We are exporting from our module menu.module.</p>
<div>
<div>The<strong> whitelistedNonPeerDependencies </strong>is to whitelist the dependent packages, if you miss this step, you will see the below error.</div>
<div>
<pre class="EnlighterJSRAW" data-enlighter-language="null">Distributing npm packages with 'dependencies' is not recommended. Please consider adding @angular/animations to 'peerDependencies' or remove it from 'dependencies'.

BUILD ERROR
Dependency @angular/animations must be explicitly whitelisted.
</pre>
<p>Please keep in mind that if you make the property private to true, the npm will refuse to publish it, this is for avoiding accidental publication of private repositories.</p>
</div>
</div>
<h3>Run the commands and generate the dist</h3>
<p>As we have already configured our package.json file, now we can go and run the commands. Are you ready? The first thing we are going to run is &#8220;npm run packagr&#8221;. It will do the following things for you.</p>
<ul>
<li>Building Angular Package</li>
<li>Building entry point &#8216;@sibeeshpassion/org-npm-package&#8217;</li>
<li>Compiling TypeScript sources through ngc</li>
<li>Bundling to FESM2015</li>
<li>Bundling to FESM5</li>
<li>Bundling to UMD</li>
<li>Minifying UMD bundle</li>
<li>Copying declaration files</li>
<li>Writing package metadata</li>
</ul>
<p>From the image below, you can understand that it is creating a folder called dist.</p>
<p><div id="attachment_13329" style="width: 644px" class="wp-caption aligncenter"><a href="https://sibeeshpassion.com/wp-content/uploads/2018/11/npm-run-packagr-e1541451015510.png"><img decoding="async" aria-describedby="caption-attachment-13329" class="wp-image-13329 size-full" src="https://sibeeshpassion.com/wp-content/uploads/2018/11/npm-run-packagr-e1541451066893.png" alt="npm run packagr" width="634" height="237" /></a><p id="caption-attachment-13329" class="wp-caption-text">npm run packagr</p></div></p>
<p>If you just look at the dist folder you can see that all the packaging work has been done.</p>
<p><div id="attachment_13330" style="width: 644px" class="wp-caption aligncenter"><a href="https://sibeeshpassion.com/wp-content/uploads/2018/11/dist-folder-after-packaging-e1541451333557.png"><img decoding="async" aria-describedby="caption-attachment-13330" class="size-full wp-image-13330" src="https://sibeeshpassion.com/wp-content/uploads/2018/11/dist-folder-after-packaging-e1541451333557.png" alt="dist folder after packaging" width="634" height="634" /></a><p id="caption-attachment-13330" class="wp-caption-text">dist folder after packaging</p></div></p>
<h3>Publishing your package to NPM registry</h3>
<p>As our package is ready, we can go ahead and start publishing our package to the NPM registry.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">npm publish dist</pre>
<p>When you run the above command, if you haven&#8217;t signed up for private packages, you will get an error as below.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">npm ERR! publish Failed PUT 402
npm ERR! code E402
npm ERR! You must sign up for private packages : @sibeeshpassion/org-npm-package</pre>
<p>Let&#8217;s just publish this package publically now, so that I don&#8217;t want to pay anything. Before you do that, go to your package.json file and change the name from &#8220;name&#8221;: &#8220;@sibeeshpassion/org-npm-package&#8221; to &#8220;name&#8221;: &#8220;org-npm-package&#8221;. Run &#8220;npm run packagr&#8221; again. It will update your dist folder with the new files. The contents of the dist folder will be a little than the one we had for our organization.</p>
<p><div id="attachment_13331" style="width: 644px" class="wp-caption aligncenter"><a href="https://sibeeshpassion.com/wp-content/uploads/2018/11/dist-folder-after-packaging-publically-e1541452203501.png"><img decoding="async" aria-describedby="caption-attachment-13331" class="size-full wp-image-13331" src="https://sibeeshpassion.com/wp-content/uploads/2018/11/dist-folder-after-packaging-publically-e1541452203501.png" alt="dist folder after packaging publically" width="634" height="621" /></a><p id="caption-attachment-13331" class="wp-caption-text">dist folder after packaging publically</p></div></p>
<p>Let&#8217;s just run &#8220;npm publish dist&#8221; again, this time we should not see any errors. Please be noted that you should run &#8220;npm login&#8221; before you run npm publish command.</p>
<p><div id="attachment_13333" style="width: 644px" class="wp-caption aligncenter"><a href="https://sibeeshpassion.com/wp-content/uploads/2018/11/npm-publish-dist-e1541452493726.png"><img decoding="async" aria-describedby="caption-attachment-13333" class="wp-image-13333 size-full" src="https://sibeeshpassion.com/wp-content/uploads/2018/11/npm-publish-dist-e1541452540426.png" alt="npm publish dist" width="634" height="214" /></a><p id="caption-attachment-13333" class="wp-caption-text">npm publish dist</p></div></p>
<p>Now if you look at <a href="https://www.npmjs.com/~sibeeshvenu">your NPM registry</a> you should be able to see <a href="https://www.npmjs.com/package/org-npm-package">your package</a>.</p>
<h2>Using the package in another solution</h2>
<p>Wow!, we have successfully created an Angular NPM package, now we can easily use the same in our other applications. Let&#8217;s just create another application.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">ng new use-org-npm-package</pre>
<p>Once the application is been created, let&#8217;s just install the new package we have created.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">npm i org-npm-package</pre>
<p>Now, we can add our MenuModule to the new application&#8217;s app.module.ts file.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { MenuModule } from 'org-npm-package';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    MenuModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</pre>
<p>The only thing pending now is, to use the app-ng-private-menu in your app.component.html.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">&lt;app-ng-private-menu&gt;&lt;/app-ng-private-menu&gt;</pre>
<h2>Output</h2>
<p>Let&#8217;s just run our new application and see everything is working as expected.</p>
<p><div id="attachment_13334" style="width: 644px" class="wp-caption aligncenter"><a href="https://sibeeshpassion.com/wp-content/uploads/2018/11/my-own-npm-package-e1541453211484.png"><img decoding="async" aria-describedby="caption-attachment-13334" class="wp-image-13334 size-full" src="https://sibeeshpassion.com/wp-content/uploads/2018/11/my-own-npm-package-e1541453246899.png" alt="my own npm package" width="634" height="617" /></a><p id="caption-attachment-13334" class="wp-caption-text">my own npm package</p></div></p>
<div class="mceTemp"></div>
<h2><span id="conclusion_1"><span id="conclusion">Conclusion</span></span></h2>
<p>Congratulation, you have created and used your own NPM package. In this article, we have learned how to,</p>
<ol>
<li>Create an angular 7 application</li>
<li>Create a Private NPM package</li>
<li>Create a Public NPM package</li>
<li>Publish a package to NPM registry</li>
<li>Use the created package in another solution</li>
</ol>
<p>We will make this package to accept the properties while using the same so that we can easily pass the menu items from the application where this package is being consumed. Isn&#8217;t that the way to make a package reusable? Please feel free to play with this GitHub repository. Please do share me your findings while you work on the same. I really appreciate that, thanks in advance.</p>
<h2><span id="your-turn-what-do-you-think">Your turn. What do you think?</span></h2>
<p>Thanks a lot for reading. I will come back with another post on the same topic very soon. Did I miss anything that you may think which is needed? Could you find this post as useful? Kindly do not forget to share me your feedback.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/create-your-own-npm-package-private-or-public/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>New Angular Drag and Drop Feature &#8211; ngDragDrop</title>
		<link>https://sibeeshpassion.com/new-angular-drag-and-drop-feature-ngdragdrop/</link>
					<comments>https://sibeeshpassion.com/new-angular-drag-and-drop-feature-ngdragdrop/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Tue, 30 Oct 2018 08:11:49 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[angular-cdk-drag-drop]]></category>
		<category><![CDATA[Angular7]]></category>
		<category><![CDATA[drag-drop]]></category>
		<category><![CDATA[DragDropModule]]></category>
		<category><![CDATA[HttpModule]]></category>
		<category><![CDATA[ngDragDrop]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=13319</guid>

					<description><![CDATA[[toc] Introduction As you all know that Angular 7 is out with some cool new features. I really appreciate that you wanted to experience the brand new Angular. Here in this post, I am going to explain a bit about one of the Angular 7 feature, which is Drag and Drops. At the end of this article, you will have an application which fetches the real data from the database and binds it to the UI and then performs multi-directional drag and drops. Enough talking, let&#8217;s jump into the setup. I hope you will find this post useful. Source Code The [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h2>Introduction</h2>
<p>As you all know that Angular 7 is out with some cool new features. I really appreciate that you wanted to experience the brand new <a href="https://sibeeshpassion.com/category/angular/">Angular</a>. Here in this post, I am going to explain a bit about one of the Angular 7 feature, which is Drag and Drops. At the end of this article, you will have an application which fetches the real data from the database and binds it to the UI and then performs multi-directional drag and drops. Enough talking, let&#8217;s jump into the setup. I hope you will find this post useful.</p>
<h2>Source Code</h2>
<p>The source code can be found <a href="https://github.com/SibeeshVenu/ngDragDrop">here</a>.</p>
<h2>Background</h2>
<p>As Angular 7 is out last week, I wanted to try a few things with the same and that is the cause for this article. If you are really new to Angular, and if you need to try some other things, <a href="https://sibeeshpassion.com/category/angular/">visiting my articles</a> on the same topic wouldn&#8217;t be a bad idea.</p>
<h2>Creating ngDragDrop app</h2>
<p>The first thing we are going to do is to create a dummy application.</p>
<h3>Installing Angular CLI</h3>
<p>Yes, as you guessed, we are using Angular CLI. If you haven&#8217;t installed Angular CLI, I recommend you to install the same. It is a great CLI tool for Angular, I am sure you will love that. You can do that by running the below command.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">npm install -g @angular/cli</pre>
<p>Once we set up this project we will be using the Angular CLI commands and you can see <a href="https://cli.angular.io/">here</a> for understanding the things you can do with the CLI.</p>
<h3>Generating a new project</h3>
<p>Now it is time to generate our new project. We can use the below command for the same.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">ng new ngDragDrop</pre>
<p>And you will be able to see all the hard work this CLI is doing for us. Now that we have created our application, let&#8217;s run our application and see if it is working or not.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">ng serve --open (if you need to open the browser by the app)
ng serve (if you want to manually open the browser).
You can always use 'ng s' as well
</pre>
<p><span style="font-size: 14px;">The command will build your application and run it in the browser.</span></p>
<p>As we develop we will be using the Angular material for the design and we can install it now itself along with the animation and cdk. With the Angular 6+ versions you can also do this by following the below command.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">ng add @angular/material</pre>
<h3>Generate and set up header component</h3>
<p>Now we have an application to work with and let&#8217;s create a header component now.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">ng g c header</pre>
<p>The above command will generate all the files you need to work with and it will also add this component to the app.module.ts. I am going to edit only the HTML of the header component for myself and not going to add any logic. You can add anything you wish.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">&lt;div style="text-align:center"&gt;
  &lt;h1&gt;
    Welcome to ngDragDropg at &lt;a href="https://sibeeshpassion.com"&gt;Sibeesh Passion&lt;/a&gt;
  &lt;/h1&gt;
&lt;/div&gt;</pre>
<h3>Set up footer component</h3>
<p>Create the footer component by running the below command.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">ng g c footer</pre>
<p>And you can edit or style them as you wish.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">&lt;p&gt;
  Copyright @SibeeshPassion 2018 - 2019 :)
&lt;/p&gt;
</pre>
<h3>Set up app-routing.module.ts</h3>
<p>We are going to create a route only for home.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
  {
    path: '',
    redirectTo: '/home',
    pathMatch: 'full'
  },
  {
    path: 'home',
    component: HomeComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
</pre>
<h3>Set up router outlet in app.component.html</h3>
<p>Now we have a route and it is time to set up the outlet.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">&lt;app-header&gt;&lt;/app-header&gt;
&lt;router-outlet&gt;
&lt;/router-outlet&gt;
&lt;app-footer&gt;&lt;/app-footer&gt;</pre>
<h3>Set up app.module.ts</h3>
<p>Every Angular app will be having at least one NgModule class <code>AppModule</code>resides in <code>app.module.ts</code>. You can always learn about the Angular architecture <a href="https://angular.io/guide/architecture-modules">here</a>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { MatButtonModule, MatCheckboxModule, MatMenuModule, MatCardModule, MatSelectModule } from '@angular/material';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { FooterComponent } from './footer/footer.component';
import { HomeComponent } from './home/home.component';
import { MovieComponent } from './movie/movie.component';
import { MovieService } from './movie.service';
import { HttpModule } from '@angular/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { DragDropModule } from '@angular/cdk/drag-drop';

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    FooterComponent,
    HomeComponent,
    MovieComponent
  ],
  exports: [
    HttpModule,
    BrowserModule,
    AppRoutingModule,
    DragDropModule,
    MatButtonModule, MatCheckboxModule, MatMenuModule, MatCardModule, MatSelectModule, BrowserAnimationsModule
  ],
  imports: [
    HttpModule,
    BrowserModule,
    AppRoutingModule,
    DragDropModule,
    MatButtonModule, MatCheckboxModule, MatMenuModule, MatCardModule, MatSelectModule, BrowserAnimationsModule
  ],
  providers: [MovieService],
  bootstrap: [AppComponent]
})
export class AppModule { }
</pre>
<p>Do you see a DragDropModule there? You should import it to use the drag and drop feature and it resides in the @angular/cdk/drag-drop. As you might have already noticed, we have added one service called MovieService in the providers array. We will create one now.</p>
<h3>Creating a movie service</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="null">import { Injectable } from '@angular/core';
import { RequestMethod, RequestOptions, Request, Http } from '@angular/http';
import { config } from './config';

@Injectable({
  providedIn: 'root'
})
export class MovieService {
  constructor(private http: Http) {
  }

  async get(url: string) {
    return await this.request(url, RequestMethod.Get);
  }

  async request(url: string, method: RequestMethod) {
    const requestOptions = new RequestOptions({
      method: method,
      url: `${config.api.baseUrl}${url}${config.api.apiKey}`
    });

    const request = new Request(requestOptions);
    return await this.http.request(request).toPromise();
  }
}
</pre>
<p>As you can see I haven&#8217;t done much with the service class and didn&#8217;t implement the error mechanism and other things as I wanted to make this as short as possible. This service will fetch the movies from an online database <a href="https://www.themoviedb.org/">TMDB</a> and here in this article and repository, I am using mine. I strongly recommend you to create your own instead of using the one mentioned here. Can we set up the config file now?</p>
<h3>Set up config.ts</h3>
<p>A configuration file is a way to arrange things in handy and you must implement in all the projects you are working with.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">const config = {
    api: {
        baseUrl: 'https://api.themoviedb.org/3/movie/',
        apiKey: '&amp;api_key=c412c072676d278f83c9198a32613b0d',
        topRated: 'top_rated?language=en-US&amp;page=1'
    }
};
export { config };
</pre>
<h3>Creating a movie component</h3>
<p>Let&#8217;s create a new component now to load the movie into it. Basically, we will be using this movie component inside the cdkDropList div. Our movie component will be having the HTML as below.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">&lt;mat-card&gt;
  &lt;img mat-card-image src="https://image.tmdb.org/t/p/w185_and_h278_bestv2/{{movie?.poster_path}}" &gt;
&lt;/mat-card&gt;</pre>
<p>I just made it as simple as is. But if future we can add a few more properties for the movie component and show them here. The typescript file will be having one property with @Input decorator so that we can input the values to it from the home component.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">import { Component, OnInit, Input } from '@angular/core';
import { Movie } from '../models/movie';

@Component({
  selector: 'app-movie',
  templateUrl: './movie.component.html',
  styleUrls: ['./movie.component.scss']
})
export class MovieComponent implements OnInit {
  @Input()
  movie: Movie;
  
  constructor() { 
  }

  ngOnInit() {
  }

}
</pre>
<p>Below is my model movie.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">export class Movie {
    poster_path: string;
}
</pre>
<p>As I said, it has only one property now, will add a few later.</p>
<h3>Set up home component</h3>
<p>Now here is the main part, the place where we render our movies and perform drag and drop. I will be having a parent container as<code class="EnlighterJSRAW" data-enlighter-language="null">&lt;div style="display: flex;"&gt;</code> so that the inner divs will be arranged horizontally. And I will be having two inner containers, one is to show all the movies and another one is to show the movies I am going to watch. I can just drag the movie from the left container to right and vice versa. Let&#8217;s design the HTML now. Below is all the movie collection.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">&lt;div cdkDropList #allmovies="cdkDropList" [cdkDropListData]="movies" [cdkDropListConnectedTo]="[towatch]" (cdkDropListDropped)="drop($event)"&gt;
    &lt;app-movie *ngFor="let movie of movies" [movie]="movie" cdkDrag&gt;&lt;/app-movie&gt;
&lt;/div&gt;</pre>
<p>As you can see that there are a few new properties I am assigning to both the app-movie and app-movie container.</p>
<div>
<ul>
<li>cdkDropList is basically a container for the drag and drop items</li>
<li>
<div>
<div>#allmovies=&#8221;cdkDropList&#8221; is the id of our source container</div>
</div>
<div></div>
</li>
<li>
<div>
<div>
<div>[cdkDropListConnectedTo]=&#8221;[towatch]&#8221; is how we are connecting two app-movie containers, remember the &#8220;towatch&#8221; is the id of another cdkDropList container</div>
</div>
</div>
<div></div>
</li>
<li>
<div>
<div>
<div>[cdkDropListData]=&#8221;movies&#8221; is how we assign the source data to the list</div>
</div>
</div>
<div></div>
</li>
<li>
<div>
<div>
<div>(cdkDropListDropped)=&#8221;drop($event)&#8221; is the callback event whenever there is a drag and drop happening.</div>
</div>
</div>
<div></div>
</li>
<li>Inside the cdkDropList container, we are looping through the values and pass the movie to our own movie component which is app-movie</li>
<li>We should also add the property cdkDrag in our Draggable item, which is nothing but a movie.</li>
</ul>
<p>Now let us create another container which will be the collection of movies which I am going to watch.</p>
<div>
<pre class="EnlighterJSRAW" data-enlighter-language="null">&lt;div cdkDropList #towatch="cdkDropList" [cdkDropListData]="moviesToWatch" [cdkDropListConnectedTo]="[allmovies]" (cdkDropListDropped)="drop($event)"&gt;
    &lt;app-movie *ngFor="let movie of moviesToWatch" [movie]="movie" cdkDrag&gt;&lt;/app-movie&gt;
&lt;/div&gt;</pre>
<p>As you can see we are almost using the same properties as we did for the first container except for the id, cdkDropListData, cdkDropListConnectedTo.</p>
<p>Finally, our home.component.html will be as follows.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">&lt;div style="display: flex;"&gt;
  &lt;div class="container"&gt;
    &lt;div class="row"&gt;
      &lt;h2 style="text-align: center"&gt;Movies&lt;/h2&gt;
      &lt;div  cdkDropList #allmovies="cdkDropList" [cdkDropListData]="movies" [cdkDropListConnectedTo]="[towatch]"
        (cdkDropListDropped)="drop($event)"&gt;
        &lt;app-movie *ngFor="let movie of movies" [movie]="movie" cdkDrag&gt;&lt;/app-movie&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
  &lt;div class="container"&gt;
    &lt;div class="row"&gt;
      &lt;h2 style="text-align: center"&gt;Movies to watch&lt;/h2&gt;
      &lt;div cdkDropList #towatch="cdkDropList" [cdkDropListData]="moviesToWatch" [cdkDropListConnectedTo]="[allmovies]"
        (cdkDropListDropped)="drop($event)"&gt;
        &lt;app-movie *ngFor="let movie of moviesToWatch" [movie]="movie" cdkDrag&gt;&lt;/app-movie&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;</pre>
<p>Now we need to get some data by calling our service, let&#8217;s open our home.component.ts file.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">import { Component } from '@angular/core';
import { MovieService } from '../movie.service';
import { Movie } from '../models/movie';
import { config } from '../config';
import { CdkDragDrop, moveItemInArray, transferArrayItem } from '@angular/cdk/drag-drop';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})

export class HomeComponent {
  movies: Movie[];
  moviesToWatch: Movie[] = [{
    poster_path: '/uC6TTUhPpQCmgldGyYveKRAu8JN.jpg'
  }];
  constructor(private movieService: MovieService) {
    this.getMovies();
  }
  private async getMovies() {
    const movies = await this.movieService.get(config.api.topRated);
    return this.formatDta(movies.json().results);
  }
  formatDta(_body: Movie[]): void {
    this.movies = _body.filter(movie =&gt; movie.poster_path !== '/uC6TTUhPpQCmgldGyYveKRAu8JN.jpg');
  }
  drop(event: CdkDragDrop&lt;string[]&gt;) {
    if (event.previousContainer === event.container) {
      moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
    } else {
      transferArrayItem(event.previousContainer.data,
        event.container.data,
        event.previousIndex,
        event.currentIndex);
    }
  }
}
</pre>
<p>Here I am importing CdkDragDrop, moveItemInArray, transferArrayItem from &#8216;@angular/cdk/drag-drop&#8217;, this helps us to perform the drag and drop. In the constructor, we are fetching the data and assign to the variable movies which are an array of the movie.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">private async getMovies() {
    const movies = await this.movieService.get(config.api.topRated);
    return this.formatDta(movies.json().results);
}</pre>
<p>I am setting the movies to watch collection as below, as I have already planned to watch that movie.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">moviesToWatch: Movie[] = [{
    poster_path: '/uC6TTUhPpQCmgldGyYveKRAu8JN.jpg'
  }];</pre>
<p>Remember the drag and drop with two sources will not work if it doesn&#8217;t have at least one item in it. Because I set a movie in it, it doesn&#8217;t make any sense to show that movie in the other collection right?</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">formatDta(_body: Movie[]): void {
   this.movies = _body.filter(movie =&gt; movie.poster_path !== '/uC6TTUhPpQCmgldGyYveKRAu8JN.jpg');
}</pre>
<p>And below is our drop event.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">drop(event: CdkDragDrop&lt;string[]&gt;) {
   if (event.previousContainer === event.container) {
     moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
   } else {
     transferArrayItem(event.previousContainer.data,
       event.container.data,
       event.previousIndex,
       event.currentIndex);
   }
 }</pre>
<p>The complete code for the home.component.ts will look like below.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">import { Component } from '@angular/core';
import { MovieService } from '../movie.service';
import { Movie } from '../models/movie';
import { config } from '../config';
import { CdkDragDrop, moveItemInArray, transferArrayItem } from '@angular/cdk/drag-drop';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})

export class HomeComponent {
  movies: Movie[];
  moviesToWatch: Movie[] = [{
    poster_path: '/uC6TTUhPpQCmgldGyYveKRAu8JN.jpg'
  }];
  constructor(private movieService: MovieService) {
    this.getMovies();
  }
  private async getMovies() {
    const movies = await this.movieService.get(config.api.topRated);
    return this.formatDta(movies.json().results);
  }
  formatDta(_body: Movie[]): void {
    this.movies = _body.filter(movie =&gt; movie.poster_path !== '/uC6TTUhPpQCmgldGyYveKRAu8JN.jpg');
  }
  drop(event: CdkDragDrop&lt;string[]&gt;) {
    if (event.previousContainer === event.container) {
      moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
    } else {
      transferArrayItem(event.previousContainer.data,
        event.container.data,
        event.previousIndex,
        event.currentIndex);
    }
  }
}
</pre>
<p>&nbsp;</p>
</div>
</div>
<h3>Custom styling</h3>
<p>I have applied some custom styles to some components, those are below.</p>
<h4>home.component.scss</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="null">.container{
  border: 1px solid rgb(248, 144, 144);
  margin: 5%;
  overflow: auto;
  width: 40%;
  height: 500px;
}
app-movie{
  cursor: move;
  width: 50%;
  display: inline-flex;
}</pre>
<h4>movie.component.scss</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="null">mat-card{
    width: 70%;
    padding: 26px;
    margin: 5px;
    border: 1px solid;
}</pre>
<h2>Output</h2>
<p>Once you have implemented all the steps, you will be having an application which uses Angular 7 Drag and Drop with actual server data. Now let us run the application and see it in action.</p>
<p><div id="attachment_13320" style="width: 658px" class="wp-caption aligncenter"><a href="https://sibeeshpassion.com/wp-content/uploads/2018/10/ngDragDrop-Initial.png"><img decoding="async" aria-describedby="caption-attachment-13320" class="size-full wp-image-13320" src="https://sibeeshpassion.com/wp-content/uploads/2018/10/ngDragDrop-Initial.png" alt="ngDragDrop Initial" width="648" height="510" srcset="/wp-content/uploads/2018/10/ngDragDrop-Initial.png 648w, /wp-content/uploads/2018/10/ngDragDrop-Initial-300x236.png 300w, /wp-content/uploads/2018/10/ngDragDrop-Initial-400x315.png 400w" sizes="(max-width: 648px) 100vw, 648px" /></a><p id="caption-attachment-13320" class="wp-caption-text">ngDragDrop Initial</p></div></p>
<p><div id="attachment_13321" style="width: 661px" class="wp-caption aligncenter"><a href="https://sibeeshpassion.com/wp-content/uploads/2018/10/ngDragDrop-After-Adding.png"><img decoding="async" aria-describedby="caption-attachment-13321" class="size-full wp-image-13321" src="https://sibeeshpassion.com/wp-content/uploads/2018/10/ngDragDrop-After-Adding.png" alt="ngDragDrop After Adding" width="651" height="517" srcset="/wp-content/uploads/2018/10/ngDragDrop-After-Adding.png 651w, /wp-content/uploads/2018/10/ngDragDrop-After-Adding-300x238.png 300w, /wp-content/uploads/2018/10/ngDragDrop-After-Adding-400x318.png 400w" sizes="(max-width: 651px) 100vw, 651px" /></a><p id="caption-attachment-13321" class="wp-caption-text">ngDragDrop After Adding</p></div></p>
<p><div id="attachment_13322" style="width: 661px" class="wp-caption aligncenter"><a href="https://sibeeshpassion.com/wp-content/uploads/2018/10/ngDragDrop-adding-more.png"><img decoding="async" aria-describedby="caption-attachment-13322" class="size-full wp-image-13322" src="https://sibeeshpassion.com/wp-content/uploads/2018/10/ngDragDrop-adding-more.png" alt="ngDragDrop adding more" width="651" height="515" srcset="/wp-content/uploads/2018/10/ngDragDrop-adding-more.png 651w, /wp-content/uploads/2018/10/ngDragDrop-adding-more-300x237.png 300w, /wp-content/uploads/2018/10/ngDragDrop-adding-more-400x316.png 400w" sizes="(max-width: 651px) 100vw, 651px" /></a><p id="caption-attachment-13322" class="wp-caption-text">ngDragDrop adding more</p></div></p>
<p>&nbsp;</p>
<h2><span id="conclusion_1"><span id="conclusion">Conclusion</span></span></h2>
<p>In this post, we have learned how to,</p>
<ol>
<li>Create an angular 7 application</li>
<li>Work with Angular CLI</li>
<li>Generate a service in Angular</li>
<li>How to fetch data from the server using HttpModule</li>
<li>Generate components in Angular</li>
<li>Use Material design</li>
<li>Work with Angular 7 Drag and Drop feature with real server data</li>
</ol>
<p>Please feel free to play with this GitHub repository. Please do share me your findings while you work on the same. I really appreciate that, thanks in advance.</p>
<h2><span id="your-turn-what-do-you-think">Your turn. What do you think?</span></h2>
<p>Thanks a lot for reading. I will come back with another post on the same topic very soon. Did I miss anything that you may think which is needed? Could you find this post as useful? If yes, please like/share/clap for me.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/new-angular-drag-and-drop-feature-ngdragdrop/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Angular Virtual Scrolling &#8211; ngVirtualScrolling</title>
		<link>https://sibeeshpassion.com/angular-virtual-scrolling-ngvirtualscrolling/</link>
					<comments>https://sibeeshpassion.com/angular-virtual-scrolling-ngvirtualscrolling/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Wed, 24 Oct 2018 20:12:26 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[Angular 7]]></category>
		<category><![CDATA[cdk-virtual-scroll-viewport]]></category>
		<category><![CDATA[Deferred Scrolling]]></category>
		<category><![CDATA[ng]]></category>
		<category><![CDATA[ngVirtualScrolling]]></category>
		<category><![CDATA[ScrollingModule]]></category>
		<category><![CDATA[Virtual Scrolling]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=13300</guid>

					<description><![CDATA[[toc] Introduction Yes!. Angular 7 is out with some cool new features. I really appreciate that you wanted to experience the brand new Angular. Here in this post, I am going to explain a bit about one of the Angular 7 feature, which is Virtual Scrolling. At the end of this article, you will have an application which fetches the real data from the database and binds it to the UI by using Virtual Scrolling feature. I am not sure about you, but I am super excited to develop a sample application with this feature. Enough talking, let&#8217;s jump into [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h2>Introduction</h2>
<p>Yes!. Angular 7 is out with some cool new features. I really appreciate that you wanted to experience the brand new <a href="https://sibeeshpassion.com/category/angular/">Angular</a>. Here in this post, I am going to explain a bit about one of the Angular 7 feature, which is Virtual Scrolling. At the end of this article, you will have an application which fetches the real data from the database and binds it to the UI by using Virtual Scrolling feature. I am not sure about you, but I am super excited to develop a sample application with this feature. Enough talking, let&#8217;s jump into the setup. I hope you will find this pose useful.</p>
<h2>Source Code</h2>
<p>The source code can be found <a href="https://github.com/SibeeshVenu/ngVirtualScrolling">here</a>.</p>
<h2>Background</h2>
<p>As Angular 7 is out last week, I wanted to try a few things with the same and that is the cause for this article. If you are really new to Angular, and if you need to try some other things, <a href="https://sibeeshpassion.com/category/angular/">visiting my articles</a> on the same topic wouldn&#8217;t be a bad idea.</p>
<h2>Creating ngVirtualScrolling app</h2>
<p>The first thing we are going to do is to create a dummy application.</p>
<h3>Installing Angular CLI</h3>
<p>Yes, as you guessed, we are using Angular CLI. If you haven&#8217;t installed Angular CLI, I recommend you to install the same. It is a great CLI tool for Angular, I am sure you will love that. You can do that by running the below command.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">npm install -g @angular/cli</pre>
<p>Once we set up this project we will be using the Angular CLI commands and you can see <a href="https://cli.angular.io/">here</a> for understanding the things you can do with the CLI.</p>
<h3>Generating a new project</h3>
<p>Now it is time to generate our new project. We can use the below command for the same.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">ng new ngVirtualScrolling</pre>
<p>And you will be able to see all the hard work this CLI is doing for us.</p>
<p><div id="attachment_13302" style="width: 660px" class="wp-caption alignnone"><a href="https://sibeeshpassion.com/wp-content/uploads/2018/10/Generate-ng-project-e1540406786190.png"><img decoding="async" aria-describedby="caption-attachment-13302" class="size-full wp-image-13302" src="https://sibeeshpassion.com/wp-content/uploads/2018/10/Generate-ng-project-e1540406786190.png" alt="Generate ng project" width="650" height="498" /></a><p id="caption-attachment-13302" class="wp-caption-text">Generate ng project</p></div></p>
<p>Now that we have created our application, let&#8217;s run our application and see if it is working or not.</p>
<p><div id="attachment_13303" style="width: 644px" class="wp-caption alignnone"><a href="https://sibeeshpassion.com/wp-content/uploads/2018/10/Build-and-open-in-browser-e1540407077398.png"><img decoding="async" aria-describedby="caption-attachment-13303" class="wp-image-13303" src="https://sibeeshpassion.com/wp-content/uploads/2018/10/Build-and-open-in-browser-e1540407077398.png" alt="Build and open in browser" width="634" height="160" /></a><p id="caption-attachment-13303" class="wp-caption-text">Build and open in browser</p></div></p>
<p>As we develop we will be using the Angular material for the design and we can install it now itself along with the animation and cdk.</p>
<p><div id="attachment_13304" style="width: 1034px" class="wp-caption alignnone"><a href="https://sibeeshpassion.com/wp-content/uploads/2018/10/install-material-cdk-and-animation.png"><img decoding="async" aria-describedby="caption-attachment-13304" class="wp-image-13304 size-large" src="https://sibeeshpassion.com/wp-content/uploads/2018/10/install-material-cdk-and-animation-1024x54.png" alt="install material, cdk and animation" width="1024" height="54" srcset="/wp-content/uploads/2018/10/install-material-cdk-and-animation-1024x54.png 1024w, /wp-content/uploads/2018/10/install-material-cdk-and-animation-300x16.png 300w, /wp-content/uploads/2018/10/install-material-cdk-and-animation-768x40.png 768w, /wp-content/uploads/2018/10/install-material-cdk-and-animation-400x21.png 400w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><p id="caption-attachment-13304" class="wp-caption-text">install material, cdk, and animation</p></div></p>
<p>With the Angular 6+ versions you can also do this by following the below command.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">ng add @angular/material</pre>
<h3>Generating components</h3>
<p>Now our project is ready and we can start creating the components, again, CLI is going to do the work for us for free. If it is a freelance developer, how much would you pay him/her?</p>
<p><div id="attachment_13305" style="width: 1034px" class="wp-caption alignnone"><a href="https://sibeeshpassion.com/wp-content/uploads/2018/10/ng-c-home.png"><img decoding="async" aria-describedby="caption-attachment-13305" class="size-large wp-image-13305" src="https://sibeeshpassion.com/wp-content/uploads/2018/10/ng-c-home-1024x116.png" alt="ng c home" width="1024" height="116" srcset="/wp-content/uploads/2018/10/ng-c-home-1024x116.png 1024w, /wp-content/uploads/2018/10/ng-c-home-300x34.png 300w, /wp-content/uploads/2018/10/ng-c-home-768x87.png 768w, /wp-content/uploads/2018/10/ng-c-home-400x45.png 400w, /wp-content/uploads/2018/10/ng-c-home.png 1626w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><p id="caption-attachment-13305" class="wp-caption-text">ng g c home</p></div></p>
<p><div id="attachment_13306" style="width: 1034px" class="wp-caption alignnone"><a href="https://sibeeshpassion.com/wp-content/uploads/2018/10/ng-c-header.png"><img decoding="async" aria-describedby="caption-attachment-13306" class="size-large wp-image-13306" src="https://sibeeshpassion.com/wp-content/uploads/2018/10/ng-c-header-1024x135.png" alt="ng g c header" width="1024" height="135" srcset="/wp-content/uploads/2018/10/ng-c-header-1024x135.png 1024w, /wp-content/uploads/2018/10/ng-c-header-300x40.png 300w, /wp-content/uploads/2018/10/ng-c-header-768x101.png 768w, /wp-content/uploads/2018/10/ng-c-header-400x53.png 400w, /wp-content/uploads/2018/10/ng-c-header.png 1690w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><p id="caption-attachment-13306" class="wp-caption-text">ng g c header</p></div></p>
<p><div id="attachment_13307" style="width: 1034px" class="wp-caption alignnone"><a href="https://sibeeshpassion.com/wp-content/uploads/2018/10/ng-c-footer.png"><img decoding="async" aria-describedby="caption-attachment-13307" class="size-large wp-image-13307" src="https://sibeeshpassion.com/wp-content/uploads/2018/10/ng-c-footer-1024x114.png" alt="ng g c footer" width="1024" height="114" srcset="/wp-content/uploads/2018/10/ng-c-footer-1024x114.png 1024w, /wp-content/uploads/2018/10/ng-c-footer-300x33.png 300w, /wp-content/uploads/2018/10/ng-c-footer-768x85.png 768w, /wp-content/uploads/2018/10/ng-c-footer-400x44.png 400w, /wp-content/uploads/2018/10/ng-c-footer.png 1627w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><p id="caption-attachment-13307" class="wp-caption-text">ng g c footer</p></div></p>
<p>Now we have three components to work with. So let&#8217;s begin.</p>
<h3>Set up header component</h3>
<p>I am going to edit only the HTML of the header component for myself and not going to add any logic. You can add anything you wish.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">&lt;div style="text-align:center"&gt;
  &lt;h1&gt;
    Welcome to ngVirtualScrolling at &lt;a href="https://sibeeshpassion.com"&gt;Sibeesh Passion&lt;/a&gt;
  &lt;/h1&gt;
&lt;/div&gt;</pre>
<h3>Set up footer component</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="null">&lt;p&gt;
  Copyright @SibeeshPassion 2018 - 2019 :)
&lt;/p&gt;
</pre>
<h3>Set up app-routing.module.ts</h3>
<p>We are going to create a route only for home.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
  {
    path: '',
    redirectTo: '/home',
    pathMatch: 'full'
  },
  {
    path: 'home',
    component: HomeComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
</pre>
<h3>Set up router outlet in app.component.html</h3>
<p>Now we have a route and it is time to set up the outlet.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">&lt;app-header&gt;&lt;/app-header&gt;
&lt;router-outlet&gt;
&lt;/router-outlet&gt;
&lt;app-footer&gt;&lt;/app-footer&gt;</pre>
<h3>Set up app.module.ts</h3>
<p>Every Angular app will be having at least one NgModule class, the same is named as and<code>AppModule</code> resides in a file named <code>app.module.ts</code>. You can always learn about the Angular architecture <a href="https://angular.io/guide/architecture-modules">here</a>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {MatButtonModule, MatCheckboxModule, MatMenuModule, MatCardModule, MatSelectModule} from '@angular/material';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { FooterComponent } from './footer/footer.component';
import { HomeComponent } from './home/home.component';
import { ScrollingModule } from '@angular/cdk/scrolling';
import { MovieComponent } from './movie/movie.component';
import { MovieService } from './movie.service';
import { HttpModule } from '@angular/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    FooterComponent,
    HomeComponent,
    MovieComponent
  ],
  imports: [
    HttpModule,
    BrowserModule,
    AppRoutingModule,
    ScrollingModule,
    MatButtonModule, MatCheckboxModule, MatMenuModule, MatCardModule, MatSelectModule, BrowserAnimationsModule
  ],
  exports: [
    HttpModule,
    BrowserModule,
    AppRoutingModule,
    ScrollingModule,
    MatButtonModule, MatCheckboxModule, MatMenuModule, MatCardModule, MatSelectModule
  ],
  providers: [ MovieService ],
  bootstrap: [AppComponent]
})
export class AppModule { }
</pre>
<p>Do you see a ScrollingModule there? You should import it to use the virtual scrolling and it resides in the @angular/cdk/scrolling. As you might have already noticed, we have added one service called MovieService in the providers array. We will create one now.</p>
<h3>Creating a movie service</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="null">import { Injectable } from '@angular/core';
import { RequestMethod, RequestOptions, Request, Http } from '@angular/http';
import { config } from './config';

@Injectable({
  providedIn: 'root'
})
export class MovieService {
  constructor(private http: Http) {
  }

  get(url: string) {
    return this.request(url, RequestMethod.Get)
  }

  request(url: string, method: RequestMethod): any {
    const requestOptions = new RequestOptions({
      method: method,
      url: `${config.api.baseUrl}${url}${config.api.apiKey}`
    });

    const request = new Request(requestOptions);
    return this.http.request(request);
  }
}
</pre>
<p>As you can see I haven&#8217;t done much with the service class and didn&#8217;t implement the error mechanism and other things as I wanted to make this as short as possible. This service will fetch the movies from an online database <a href="https://www.themoviedb.org/">TMDB</a> and here in this article and repository, I am using mine. I strongly recommend you to create your own instead of using mine. Can we set up the config file now?</p>
<h3>Set up config.ts</h3>
<p>A configuration file is a way to arrange things in handy and you must implement in all the projects you are working with.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">const config = {
  api: {
        baseUrl: 'https://api.themoviedb.org/3/movie/',
        apiKey:'&amp;api_key=c412c072676d278f83c9198a32613b0d',
        topRated:'top_rated?language=en-US&amp;page=1'
    }
}
export { config };</pre>
<h3>Creating a movie component</h3>
<p>Let&#8217;s create a new component now to load the movie into it. Basically, we will be using this movie component inside the cdkVirtualFor so that it will call this component each time and render it. Out movie component will be having the HTML as below.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">&lt;div class="container"&gt;
  &lt;mat-card style="min-height: 500px;" class="example-card"&gt;
    &lt;mat-card-header&gt;
      &lt;div mat-card-avatar class="example-header-image"&gt;&lt;/div&gt;
      &lt;mat-card-title&gt;{{movie?.title}}&lt;/mat-card-title&gt;
      &lt;mat-card-subtitle&gt;Release date: {{movie?.release_date}}&lt;/mat-card-subtitle&gt;
    &lt;/mat-card-header&gt;
    &lt;img mat-card-image src="https://image.tmdb.org/t/p/w370_and_h556_bestv2/{{movie?.poster_path}}" alt="{{movie?.title}}"&gt;
    &lt;mat-card-content&gt;
      &lt;p&gt;
        {{movie?.overview}}
      &lt;/p&gt;
    &lt;/mat-card-content&gt;
  &lt;/mat-card&gt;
&lt;/div&gt;</pre>
<p>And the typescript file will be having one property with @Input decorator so that we can input the values to it from the home component.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">import { Component, OnInit, Input } from '@angular/core';
import { Movie } from '../models/movie';

@Component({
  selector: 'app-movie',
  templateUrl: './movie.component.html',
  styleUrls: ['./movie.component.scss']
})
export class MovieComponent implements OnInit {
  @Input()
  movie: Movie;
  
  constructor() { 
  }

  ngOnInit() {
  }

}
</pre>
<h3>Set up home component</h3>
<p>Now here is the main part, the place where the virtual scrolling is happening. Let&#8217;s design the HTML now.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">&lt;div class="container" style="text-align:center"&gt;
  &lt;div class="row"&gt;
    &lt;cdk-virtual-scroll-viewport itemSize="500" class="example-viewport"&gt;
      &lt;app-movie *cdkVirtualFor="let movie of ds" [movie]="movie" class="example-item"&gt;{{movie || 'Loading...'}}&lt;/app-movie&gt;
    &lt;/cdk-virtual-scroll-viewport&gt;
  &lt;/div&gt;
&lt;/div&gt;</pre>
<p>Here itemSize is a mandatory property and you can give any number as per how many data you want to load to the component. We are inputting the values to our app-movie component by using [movie]=&#8221;movie&#8221;.</p>
<p>Let&#8217;s see the typescript code now.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
import { DataSource, CollectionViewer } from '@angular/cdk/collections';
import { BehaviorSubject, Subscription, Observable } from 'rxjs';
import { MovieService } from '../movie.service';
import { Movie } from '../models/movie';
import { config } from '../config';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})

export class HomeComponent {
  constructor(private movieService: MovieService) {
  }
  ds = new MyDataSource(this.movieService);
}

export class MyDataSource extends DataSource&lt;Movie | undefined&gt; {
  private page = 1;
  private initialData: Movie[] = [
    {
      id: 19404,
      title: 'Dilwale Dulhania Le Jayenge',
      overview: 'Raj is a rich, carefree, happy-go-lucky second generation NRI. Simran is the daughter of Chaudhary Baldev Singh, who in spite of being an NRI is very strict about adherence to Indian values. Simran has left for India to be married to her childhood fiancé. Raj leaves for India with a mission at his hands, to claim his lady love under the noses of her whole family. Thus begins a saga.',
      poster_path: '\/uC6TTUhPpQCmgldGyYveKRAu8JN.jpg'
    }
  ];
  private dataStream = new BehaviorSubject&lt;(Movie | undefined)[]&gt;(this.initialData)
  private subscription = new Subscription();

  constructor(private movieService: MovieService) {
    super();
  }

  connect(collectionViewer: CollectionViewer): Observable&lt;(Movie | undefined)[]&gt; {
    this.subscription.add(collectionViewer.viewChange.subscribe((range) =&gt; {
      console.log(range.start)
      console.log(range.end)
      this.movieService.get(config.api.topRated)
        .subscribe((data) =&gt; {
          this.formatDta(JSON.parse(data._body).results);
        });
    }));
    return this.dataStream;
  }

  disconnect(): void {
    this.subscription.unsubscribe();
  }

  formatDta(_body: Movie[]): void {
    this.dataStream.next(_body);
  }
}
</pre>
<p>I have a parent HomeComponent where I get the data from a class MyDataSource which extends DataSource&lt;Movie | undefined&gt;. This DataSource is an abstract class and residing in @angular/cdk/collections. As the MyDataSource class is extending from DataSource, we had to override two functions which are, connect() and disconnect(). According to the <a href="https://material.angular.io/cdk/scrolling/overview">angular material documentation</a>, The connect method will be called by the virtual scroll viewport to receive a stream that emits the data array that should be rendered. The viewport will call disconnect when the viewport is destroyed, which may be the right time to clean up any subscriptions that were registered during the connect process.</p>
<p>Inside the connect method, we are calling our own service to get the data.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">this.movieService.get(config.api.topRated)
        .subscribe((data) =&gt; {
          this.formatDta(JSON.parse(data._body).results);
        });</pre>
<h3>Custom styling</h3>
<p>I have applied some custom styles to some components, which you can see in the GitHub repository. Please copy those from there if you are creating the application from the scratch.</p>
<h2>Output</h2>
<p>Once you have implemented all the steps, you will be having an application which uses Angular 7 virtual scrolling with actual server data. Now let us run the application and see it in action.</p>
<p><div id="attachment_13309" style="width: 613px" class="wp-caption alignnone"><a href="https://sibeeshpassion.com/wp-content/uploads/2018/10/Angular-Virtual-Scrolling-Demo-Start.png"><img decoding="async" aria-describedby="caption-attachment-13309" class="size-large wp-image-13309" src="https://sibeeshpassion.com/wp-content/uploads/2018/10/Angular-Virtual-Scrolling-Demo-Start-603x1024.png" alt="Angular Virtual Scrolling Demo Start" width="603" height="1024" srcset="/wp-content/uploads/2018/10/Angular-Virtual-Scrolling-Demo-Start-603x1024.png 603w, /wp-content/uploads/2018/10/Angular-Virtual-Scrolling-Demo-Start-177x300.png 177w, /wp-content/uploads/2018/10/Angular-Virtual-Scrolling-Demo-Start-768x1305.png 768w, /wp-content/uploads/2018/10/Angular-Virtual-Scrolling-Demo-Start-400x680.png 400w, /wp-content/uploads/2018/10/Angular-Virtual-Scrolling-Demo-Start-353x600.png 353w, /wp-content/uploads/2018/10/Angular-Virtual-Scrolling-Demo-Start.png 964w" sizes="(max-width: 603px) 100vw, 603px" /></a><p id="caption-attachment-13309" class="wp-caption-text">Angular Virtual Scrolling Demo Start</p></div></p>
<p><div id="attachment_13310" style="width: 610px" class="wp-caption alignnone"><a href="https://sibeeshpassion.com/wp-content/uploads/2018/10/Angular-Virtual-Scrolling-Demo-Middle.png"><img decoding="async" aria-describedby="caption-attachment-13310" class="size-large wp-image-13310" src="https://sibeeshpassion.com/wp-content/uploads/2018/10/Angular-Virtual-Scrolling-Demo-Middle-600x1024.png" alt="Angular Virtual Scrolling Demo Middle" width="600" height="1024" srcset="/wp-content/uploads/2018/10/Angular-Virtual-Scrolling-Demo-Middle-600x1024.png 600w, /wp-content/uploads/2018/10/Angular-Virtual-Scrolling-Demo-Middle-176x300.png 176w, /wp-content/uploads/2018/10/Angular-Virtual-Scrolling-Demo-Middle-768x1310.png 768w, /wp-content/uploads/2018/10/Angular-Virtual-Scrolling-Demo-Middle-400x682.png 400w, /wp-content/uploads/2018/10/Angular-Virtual-Scrolling-Demo-Middle-352x600.png 352w, /wp-content/uploads/2018/10/Angular-Virtual-Scrolling-Demo-Middle.png 961w" sizes="(max-width: 600px) 100vw, 600px" /></a><p id="caption-attachment-13310" class="wp-caption-text">Angular Virtual Scrolling Demo Middle</p></div></p>
<p>&nbsp;</p>
<h2><span id="conclusion_1"><span id="conclusion">Conclusion</span></span></h2>
<p>In this post, we have learned how to,</p>
<ol>
<li>Create an angular 7 application</li>
<li>Work with Angular CLI</li>
<li>Generate components in Angular</li>
<li>Use Material design</li>
<li>Work with virtual scrolling in Angular 7</li>
</ol>
<p>Please feel free to play with this GitHub repository. It may not be a perfect article on this topic, so please do share me your findings while you work on the same. I really appreciate that, thanks in advance.</p>
<h2><span id="your-turn-what-do-you-think">Your turn. What do you think?</span></h2>
<p>Thanks a lot for reading. I will come back with another post on the same topic very soon. Did I miss anything that you may think which is needed? Could you find this post as useful? Please share me your valuable suggestions and feedback, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on Stack Overflow instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/angular-virtual-scrolling-ngvirtualscrolling/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>End to End (E2E) Tests in Angular Application Using Protractor</title>
		<link>https://sibeeshpassion.com/end-to-end-e2e-tests-in-angular-application-using-protractor/</link>
					<comments>https://sibeeshpassion.com/end-to-end-e2e-tests-in-angular-application-using-protractor/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Sun, 08 Jul 2018 15:25:34 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[angular-cli]]></category>
		<category><![CDATA[article]]></category>
		<category><![CDATA[E2E]]></category>
		<category><![CDATA[End to End Test]]></category>
		<category><![CDATA[Protractor]]></category>
		<category><![CDATA[Why E2E]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=13062</guid>

					<description><![CDATA[[toc] Introduction In this article, we will learn how we can create an end to end tests (e2e) for our Angular application. We will be using an existing end-to-end testing framework, which is nothing but, Protractor. Protractor runs your tests against your application running in a real browser, in the same way, your user may perform the actions. I will be using an existing application which is available in my GitHub profile. The same can be available in the source code section. Please do share your feedback with me. I hope you will like this article. Let&#8217;s start coding. Source Code The [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h2>Introduction</h2>
<p>In this article, we will learn how we can create an end to end tests (e2e) for our <a href="https://sibeeshpassion.com/category/client-side-technologies/angular/">Angular</a> application. We will be using an existing end-to-end testing framework, which is nothing but, Protractor. Protractor runs your tests against your application running in a real browser, in the same way, your user may perform the actions. I will be using an existing application which is available in my <a href="https://github.com/sibeeshvenu">GitHub</a> profile. The same can be available in the source code section. Please do share your feedback with me. I hope you will like this article. Let&#8217;s start coding.</p>
<h2>Source Code</h2>
<p>The source code can be found <a href="https://github.com/SibeeshVenu/ng5">here</a>. Please clone this repository before you start.</p>
<h2>Importance of End to End Testing</h2>
<p>Some of you might have already started writing an end to end testing for your application, and you may be knowing how important that is. Here in this section, I will list down the key benefits of an end to end testing.</p>
<ul>
<li>End to end testing tests the complete flow or the action. For example, a complete login process can be treated as one end to end testing. Basically, it tests a specific functionality.</li>
<li>It doesn&#8217;t improve the code quality as does in Unit testing. Unit testing is a different topic, and an end to end testing and unit testing are completely different.</li>
<li>As I said earlier, an end to end testing run tests on the browser, so it tests your application live, with some real data.</li>
<li>You can easily find out if any functionalities are broken because of your recent changes or implementation</li>
</ul>
<h2>Basic overview</h2>
<p>If you have already cloned the application, you should be able to see a folder e2e in your application code, open that folder. You can see 3 files as below.</p>
<ul>
<li>tsconfig.e2e.json</li>
<li>app.po.ts</li>
<li>app.e2e-spec.ts</li>
</ul>
<p>Here <em>tsconfig.e2e.json</em> is the configuration file, if you open that file, you can see that the file is been extended from <em>tsconfig.json. </em></p>
<pre class="EnlighterJSRAW" data-enlighter-language="json">{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/e2e",
    "baseUrl": "./",
    "module": "commonjs",
    "target": "es5",
    "types": [
      "jasmine",
      "jasminewd2",
      "node"
    ]
  }
}
</pre>
<p><em>app.po.ts </em>is the page object, this is really helpful and important. Here is the place, where we will write the codes to find out the elements on our page or view. So, in future, if you are changing the selectors of your element, your changes will impact only in this file, so that you don&#8217;t need to change anything in your tests. Isn&#8217;t that handy? By default, this file will have the codes as below.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { browser, by, element } from 'protractor';

export class AppPage {
  navigateTo() {
    return browser.get('/');
  }

  getParagraphText() {
    return element(by.css('app-root h1')).getText();
  }
}
</pre>
<p>As you can see, on the first line, we are importing browser, by, an element from protractor.</p>
<ol>
<li>browser, is for interacting with the browser</li>
<li>by, is for finding the element by CSS or any other function</li>
<li>element, is for converting the selected element</li>
</ol>
<p>Here in this line, element(by.css(&#8216;app-root h1&#8217;)).getText(), like you have already guessed, we are just finding an element with the selector &#8216;app-root h1&#8217;</p>
<p><em>app.e2e-spec.ts </em> is the tests holder. We will be writing all of our tests here.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { AppPage } from './app.po';

describe('my-angular5-app App', () =&gt; {
  let page: AppPage;

  beforeEach(() =&gt; {
    page = new AppPage();
  });

  it('should display welcome message', () =&gt; {
    page.navigateTo();
    expect(page.getParagraphText()).toEqual('Welcome to ng5!');
  });
});
</pre>
<p>The first thing we do is, importing the page, in this case, AppPage. This will be very easy for you if you have already written any <a href="https://sibeeshpassion.com/category/unit-testing/">unit test</a> cases using <a href="https://sibeeshpassion.com/category/unit-testing/jasmine-framework/">jasmine</a>. If you are not sure about how you can write the unit tests, I recommend you to visit this <a href="https://sibeeshpassion.com/writing-javascript-tests-using-jasmine-framework/">link</a>.</p>
<p>Once we import the page, we are declaring an object and initialize the same with an AppPage instance in <em>beforeEach</em> function, so that the code can be executed before each test runs.</p>
<p>And in our first test, we are just confirming that the title is &#8216;Welcome to app&#8217; by getting the value from our page object by calling <em>page.getParagraphText(). </em></p>
<h2>Creating Login Component</h2>
<p>As you all know, a component will have two files by default.</p>
<ul>
<li>login.component.html</li>
<li>login.component.ts</li>
</ul>
<h3>login.component.html</h3>
<p>Let&#8217;s write some HTML code for our component.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;div class="container" style="margin-top:100px;"&gt;
  &lt;div class="row justify-content-center align-items-center"&gt;
    &lt;div class="col-lg-4 col-sm-4 center-block "&gt;
      &lt;mat-card&gt;
        &lt;mat-card-header&gt;
          &lt;img mat-card-avatar src="../../../assets/images/App-login-manager-icon.png"&gt;
          &lt;mat-card-title&gt;Login here&lt;/mat-card-title&gt;
          &lt;mat-card-subtitle&gt;Trust us for your data, and sign up&lt;/mat-card-subtitle&gt;
        &lt;/mat-card-header&gt;
        &lt;mat-card-content&gt;
          &lt;div class="signup-fields"&gt;
            &lt;form id="loginForm"[formGroup]="form" (ngSubmit)="login()"&gt;
              &lt;div class="form-group"&gt;
                &lt;input name="email" class="form-control" matInput type="email" placeholder="Email" formControlName="email" /&gt;
              &lt;/div&gt;
              &lt;div class="form-group"&gt;
                &lt;input name="password" class="form-control" matInput type="password" placeholder="Password" formControlName="password" /&gt;
              &lt;/div&gt;
              &lt;div&gt;
                &lt;button id="btnSubmit" mat-raised-button type="submit" color="primary"&gt;Login&lt;/button&gt;
              &lt;/div&gt;
            &lt;/form&gt;
          &lt;/div&gt;
        &lt;/mat-card-content&gt;
      &lt;/mat-card&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;</pre>
<h3>login.component.ts</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  form;
  constructor(private fb: FormBuilder,
    private myRoute: Router,
    private auth: AuthService) {
    this.form = fb.group({
      email: ['', [Validators.required, Validators.email]],
      password: ['', Validators.required]
    });
  }

  ngOnInit() {
  }

  login() {
    if (this.form.valid) {
      this.auth.sendToken(this.form.value.email)
      this.myRoute.navigate(["home"]);
    }
  }

}
</pre>
<p>If you run the application, you can see that we are accepting the form only if we give relevant values to the fields, if not given, the form will be invalid. In our next step, we will write an end to end test for this functionality. Sounds good?</p>
<h2>Write end to end tests for Login component</h2>
<p>To get started, let us create two files as below.</p>
<ol>
<li>login.po.ts</li>
<li>login.e2e-spec.ts</li>
</ol>
<p>Now let us define our page and some functions in login.po.ts.</p>
<h3>Set up login.po.ts</h3>
<p>Open the file and write some code as preceding.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { browser, by, element } from 'protractor';

export class LoginPage {
    navigateTo(){
        return browser.get('/login');
    }
}</pre>
<p>Now we will write the codes to find the email and password text boxes.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">getEmailTextbox() {
 return element(by.name('email'));
}

getPasswordTextbox() {
 return element(by.name('password'));
}</pre>
<h3>Set up login.e2e-spec.ts</h3>
<p>It is time to set up our spec file before we start writing the tests.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { LoginPage } from './login.po';

describe('Login tests', () =&gt; {
    let page: LoginPage;

    beforeEach(() =&gt; {
        page = new LoginPage();
        page.navigateTo();        
    });
});</pre>
<p>We have imported our login page and initialized the same. It is time to write the tests now.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">it('Login form should be valid', () =&gt; {
 page.getEmailTextbox().sendKeys('info@sibeeshpassion.com');
 page.getPasswordTextbox().sendKeys('1234');

 let form = page.getForm().getAttribute('class');

 expect(form).toContain('ng-valid');
});</pre>
<p>Here what we are doing is, set the values to our text boxes by using sendKeys function and then find the class attribute of our form, so that we can check whether it is valid or not. If the form is valid, the form will be having the class as ng-valid, if not, it will have ng-invalid class.</p>
<h2>Run end to end test</h2>
<p>Running end to end test is as easy as falling off a log. As we are using Angular CLI, all we have to do is run the command <em>ng e2e. </em> This will be set in our <em>package.json </em>file.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="json">"scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  }</pre>
<p>let us run <em>ng e2e </em>now.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">PS F:\My Projects\ng5&gt; ng e2e</pre>
<p>If everything goes well, your application should open in a browser and test the functionality. You will also get a message saying &#8220;Chrome is being controlled by automated test software&#8221;.</p>
<p><div id="attachment_13064" style="width: 453px" class="wp-caption alignnone"><a href="https://sibeeshpassion.com/wp-content/uploads/2018/07/ng-e2e-browser-output.jpg"><img decoding="async" aria-describedby="caption-attachment-13064" class="size-full wp-image-13064" src="https://sibeeshpassion.com/wp-content/uploads/2018/07/ng-e2e-browser-output.jpg" alt="ng e2e browser output" width="443" height="180" srcset="/wp-content/uploads/2018/07/ng-e2e-browser-output.jpg 443w, /wp-content/uploads/2018/07/ng-e2e-browser-output-300x122.jpg 300w, /wp-content/uploads/2018/07/ng-e2e-browser-output-400x163.jpg 400w" sizes="(max-width: 443px) 100vw, 443px" /></a><p id="caption-attachment-13064" class="wp-caption-text">ng e2e browser output</p></div></p>
<p>And in your terminal console, you should see an output saying all of your tests are passed.</p>
<p><div id="attachment_13065" style="width: 644px" class="wp-caption alignnone"><a href="https://sibeeshpassion.com/wp-content/uploads/2018/07/Automated-test-output-e1531050755639.jpg"><img decoding="async" aria-describedby="caption-attachment-13065" class="size-full wp-image-13065" src="https://sibeeshpassion.com/wp-content/uploads/2018/07/Automated-test-output-e1531050755639.jpg" alt="Automated test output" width="634" height="187" /></a><p id="caption-attachment-13065" class="wp-caption-text">Automated test output</p></div></p>
<h2>Writing a few more tests</h2>
<p>Let us write a few more tests to check some other functionalities.</p>
<h3>Check form is invalid</h3>
<p>To check the form is invalid or not, we need to pass some invalid data to the form. The final test should be as follows.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">it('Login form should be invalid', () =&gt; {
 page.getEmailTextbox().sendKeys('');
 page.getPasswordTextbox().sendKeys('');

 let form = page.getForm().getAttribute('class');

 expect(form).toContain('ng-invalid');
});</pre>
<h3>Check whether the value is been saved to local storage</h3>
<p>You might have already looked at what is the functionality we are doing when we click the login button in our application. For now, we are just saving the email value to the local storage. Below is the function which gets called when we click the login button.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">login() {
    if (this.form.valid) {
      this.auth.sendToken(this.form.value.email)
      this.myRoute.navigate(["home"]);
    }
  }</pre>
<p>And this is the sendToken method in out AuthService.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">sendToken(token: string) {
    localStorage.setItem("LoggedInUser", token)
 }</pre>
<p>Now, we are going to write an automated test for this functionality. First, let us add a function which returns submit button in login.po.ts.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">getSubmitButton() {
 return element(by.css('#btnSubmit'));
}</pre>
<p>Now, write the test as preceding.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">it('Should set email value to local storage', () =&gt; {
 page.getEmailTextbox().sendKeys('info@sibeeshpassion.com');
 page.getPasswordTextbox().sendKeys('1234');

 page.getSubmitButton().click();

 let valLocalStorage = browser.executeScript("return window.localStorage.getItem('LoggedInUser');");
 expect(valLocalStorage).toEqual('info@sibeeshpassion.com');
});</pre>
<p>As you can see that, we are actually setting some valid data to the form and triggering the click event of our button, and the value of the email text box is being saved to the <a href="https://sibeeshpassion.com/?s=local+storage">localStorage</a>. In our test, we are checking the value of the localStorage by executing the script <em>browser.executeScript(&#8220;return window.localStorage.getItem(&#8216;LoggedInUser&#8217;);&#8221;). </em>We should get an output as below if everything is fine.</p>
<p><div id="attachment_13066" style="width: 644px" class="wp-caption alignnone"><a href="https://sibeeshpassion.com/wp-content/uploads/2018/07/locaStorage-in-Protractor.jpg"><img decoding="async" aria-describedby="caption-attachment-13066" class="size-full wp-image-13066" src="https://sibeeshpassion.com/wp-content/uploads/2018/07/locaStorage-in-Protractor.jpg" alt="locaStorage in Protractor" width="634" height="252" srcset="/wp-content/uploads/2018/07/locaStorage-in-Protractor.jpg 634w, /wp-content/uploads/2018/07/locaStorage-in-Protractor-300x119.jpg 300w, /wp-content/uploads/2018/07/locaStorage-in-Protractor-400x159.jpg 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-13066" class="wp-caption-text">locaStorage in Protractor</p></div></p>
<h2><span id="conclusion_1"><span id="conclusion">Conclusion</span></span></h2>
<p>Thanks a lot for reading. I will come back with another post on the same topic very soon. Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<h2><span id="your-turn-what-do-you-think">Your turn. What do you think?</span></h2>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/end-to-end-e2e-tests-in-angular-application-using-protractor/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Validation Using Template Driven Forms in Angular 5</title>
		<link>https://sibeeshpassion.com/validation-using-template-driven-forms-in-angular-5/</link>
					<comments>https://sibeeshpassion.com/validation-using-template-driven-forms-in-angular-5/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Sun, 22 Apr 2018 15:58:46 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[How to]]></category>
		<category><![CDATA[Angular 5]]></category>
		<category><![CDATA[Angular 5 Validations]]></category>
		<category><![CDATA[ng5]]></category>
		<category><![CDATA[Template Driven Forms]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=12798</guid>

					<description><![CDATA[[toc] Introduction In this post, we are going to see how to do validation using template driven forms in Angular 5, this is just a different approach that you can follow, as we have discussed another way in our previous post. At the end of this article, you will get to know how you can implement validations in Angular 5 application using Template Driven Forms. This post is a continuation of the course Developing an Angular 5 App series if you haven&#8217;t gone through the previous posts yet, I strongly recommend you to do that. You can find the links to [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h2>Introduction</h2>
<p>In this post, we are going to see how to do validation using template driven forms in <a href="http://sibeeshpassion.com/category/client-side-technologies/angular/">Angular</a> 5, this is just a different approach that you can follow, as we have discussed another way in our previous post. At the end of this article, you will get to know how you can implement validations in Angular 5 application using <em>Template Driven Forms.</em> This post is a continuation of the course <em>Developing an Angular 5 App</em> series if you haven&#8217;t gone through the previous posts yet, I strongly recommend you to do that. You can find the links to the previous posts below. I hope you will like this article.</p>
<h2><em>Developing an Angular 5 App</em> series</h2>
<p>These are the previous posts in this series. Please go ahead and have a look.</p>
<ol>
<li><a href="http://sibeeshpassion.com/what-is-new-and-how-to-set-up-our-first-angular-5-application/">What Is New and How to Set Up our First Angular 5 Application</a></li>
<li><a href="http://sibeeshpassion.com/angular-5-basic-demo-project-overview/">Angular 5 Basic Demo Project Overview</a></li>
<li><a href="http://sibeeshpassion.com/generating-your-first-components-and-modules-in-angular-5-app/">Generating Your First Components And Modules in Angular 5 App</a></li>
<li><a href="http://sibeeshpassion.com/implement-validations-in-angular-5-app/">Implement Validations in Angular 5 App</a></li>
</ol>
<h2><span id="source-code">Source Code</span></h2>
<p>You can always clone or download the source code <a href="https://github.com/SibeeshVenu/ng5">here</a></p>
<h2>Background</h2>
<p>Validations have a vital role in all application no matter in what language it is been developed. And since it is an essential part, there are many ways to achieve it. We are going to see Template Driven Forms approach here.</p>
<h2>Using the code</h2>
<p style="text-align: left;">It is recommended to clone the project from GitHub, so that you can try everything your own. Let&#8217;s go ahead and write some codes now.</p>
<h3>Install Bootstrap</h3>
<p>Before we begin, let&#8217;s install bootstrap in our application.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">PS F:\My Projects\ng5&gt; npm install bootstrap --save</pre>
<p>As we are developing this application using Angular CLI, we can add the reference of Bootstrap in our Angular-CLI.json file. The styles section of that file will look like below after you add the reference.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="json">"styles": [
        "styles.css",
        "../node_modules/bootstrap/dist/css/bootstrap.min.css"
      ]</pre>
<p>Please be noted that there are many other ways to configure Bootstrap in our application, here we are not going to explain that.</p>
<h3>Importing ngForm to a variable</h3>
<p>Let&#8217;s clean codes in our Registration component and add a new form which has a form variable, and this form variable can hold the values of our form. There are many things you can do with this variable, for now, let&#8217;s say it is our model values container.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;div class="container"&gt;
  &lt;div class="row"&gt;
    &lt;div class="no-float center-block col-lg-4 col-sm-4"&gt;
      &lt;mat-card&gt;
        &lt;mat-card-header&gt;
          &lt;img mat-card-avatar src="../../../assets/images/App-login-manager-icon.png"&gt;
          &lt;mat-card-title&gt;Sign up&lt;/mat-card-title&gt;
          &lt;mat-card-subtitle&gt;Trust us for your data, and sign up&lt;/mat-card-subtitle&gt;
        &lt;/mat-card-header&gt;
        &lt;mat-card-content&gt;
          &lt;form #regsiterForm="ngForm" (ngSubmit)="register(regsiterForm)"&gt;
          &lt;/form&gt;
        &lt;/mat-card-content&gt;
      &lt;/mat-card&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;</pre>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { OnInit, Component } from "@angular/core";

@Component({
  selector: 'app-registration',
  templateUrl: './registration.component.html',
  styleUrls: ['./registration.component.css']
})
export class RegistrationComponent implements OnInit {
  constructor() {
  }

  ngOnInit() {
  }
}


</pre>
<h3>Implement Validation for User Name field using Template Driven Forms</h3>
<p>As we have created our form, now it is time to generate out input controls into it.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;form #regsiterForm="ngForm" (ngSubmit)="register(regsiterForm)"&gt;
    &lt;div class="signup-fields"&gt;
        &lt;div class="form-group"&gt;
            &lt;input type="text" required name="userName" class="form-control" placeholder="User Name"&gt;
        &lt;/div&gt;
        &lt;div&gt;
            &lt;button class="btn btn-primary btn-block" type="submit"&gt;Signup&lt;/button&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/form&gt;</pre>
<p>What we have above is a simple HTML with template driven form, where we are going to introduce the validation. Let&#8217;s modify the userName field now.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;input type="text" [(ngModel)]="userName" #userName="ngModel" required name="userName" class="form-control" placeholder="User Name"&gt;</pre>
<p>What we are trying to achieve by the above code is, creating a reference variable userName and assign the input value to it. Basically, this is a two-way binding, where we can set the data from our component and update it in the form, and vice versa. Now if you run your application, you should see an error as below.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">Uncaught Error: Cannot assign to a reference or variable!
    at _AstToIrVisitor.visitPropertyWrite (compiler.js:26025)
    at PropertyWrite.visit (compiler.js:4585)
    at convertActionBinding (compiler.js:25475)
    at eval (compiler.js:27987)
    at Array.forEach (&lt;anonymous&gt;)
    at ViewBuilder._createElementHandleEventFn (compiler.js:27983)
    at nodes.(anonymous function) (webpack-internal:///./node_modules/@angular/compiler/esm5/compiler.js:27620:27)
    at eval (compiler.js:27928)
    at Array.map (&lt;anonymous&gt;)
    at ViewBuilder._createNodeExpressions (compiler.js:27927)</pre>
<p>This is because we are using the same name for both model and reference variable. So we should change it. To do so, let&#8217;s create a User Model (user.model.ts) and reference it to our Register component.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">export class User {
    id: any;
    userName: string;
    email: string;
    userRole: string;
    profileImage: string;
    phoneNumber: string;
    firstName: string;
    lastName: string;
}</pre>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { User } from '../models/user.model'</pre>
<p>Now we can change our input as below.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;input type="text" [(ngModel)]="user.userName" #userName="ngModel" required name="userName" class="form-control" placeholder="User Name"&gt;</pre>
<p>Please make sure that to declare a user in registration component.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">export class RegistrationComponent implements OnInit {
  user = new User();
  constructor() {
  }

  ngOnInit() {
  }
}
</pre>
<p>Now if you run your application, you can see that the Submit button will be enabled only if the form is valid, that is, only if you enter any values in the username field.</p>
<h3>Decorate the validation message</h3>
<p>Now we know that our form is working fine, but don&#8217;t we need to give a message to the users if they haven&#8217;t given any values in the fields? Let&#8217;s add few more markups in our HTML.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;div class="form-group" [class.has-error]="userName.invalid" [class.has-success]="userName.valid"&gt;
    &lt;input type="text" [(ngModel)]="user.userName" #userName="ngModel" required name="userName" class="form-control" placeholder="User Name"&gt;
    &lt;span class="help-block" *ngIf="userName.errors?.required"&gt;
                  User Name is required
                &lt;/span&gt;
&lt;/div&gt;</pre>
<p>We are enabling the class &#8220;has-error&#8221; and &#8220;has-success&#8221; dynamically by checking the valid and invalid property of userName field. We are also showing our required field message in a new span if there are any required errors in our userName model. Now if you run your app, you can see that the validation is working fine.</p>
<p><a href="https://sibeeshpassion.com/wp-content/uploads/2018/04/userName-validation-without-touch-property.jpg"><img decoding="async" class="alignnone size-full wp-image-12799" src="https://sibeeshpassion.com/wp-content/uploads/2018/04/userName-validation-without-touch-property.jpg" alt="" width="455" height="299" srcset="/wp-content/uploads/2018/04/userName-validation-without-touch-property.jpg 455w, /wp-content/uploads/2018/04/userName-validation-without-touch-property-300x197.jpg 300w, /wp-content/uploads/2018/04/userName-validation-without-touch-property-400x263.jpg 400w" sizes="(max-width: 455px) 100vw, 455px" /></a></p>
<p>But isn&#8217;t that validation showing by default, we should show the message only if the user touched our field, and refused to type anything right? Let&#8217;s add &#8220;userName.touched&#8221; in our markup.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;div class="form-group" [class.has-error]="userName.invalid &amp;&amp; userName.touched" [class.has-success]="userName.valid"&gt;
    &lt;input type="text" [(ngModel)]="user.userName" #userName="ngModel" required name="userName" class="form-control" placeholder="User Name"&gt;
    &lt;span class="help-block" *ngIf="userName.errors?.required &amp;&amp; userName.touched"&gt;
                  User Name is required
                &lt;/span&gt;
&lt;/div&gt;</pre>
<h3>Implement the validation for other fields as well</h3>
<p>Now it is time to implement the same in other fields.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;div class="container" style="margin-top:100px;"&gt;
  &lt;div class="row justify-content-center align-items-center"&gt;
    &lt;div class="col-lg-4 col-sm-4 center-block "&gt;
      &lt;mat-card&gt;
        &lt;mat-card-header&gt;
          &lt;img mat-card-avatar src="../../../assets/images/App-login-manager-icon.png"&gt;
          &lt;mat-card-title&gt;Sign up&lt;/mat-card-title&gt;
          &lt;mat-card-subtitle&gt;Trust us for your data, and sign up&lt;/mat-card-subtitle&gt;
        &lt;/mat-card-header&gt;
        &lt;mat-card-content&gt;
          &lt;form #regsiterForm="ngForm" (ngSubmit)="register(user)"&gt;
            &lt;div class="signup-fields"&gt;
              &lt;div class="form-group" [class.has-error]="userName.invalid &amp;&amp; userName.touched" [class.has-success]="userName.valid"&gt;
                &lt;input type="text" [(ngModel)]="user.userName" #userName="ngModel" required name="userName" class="form-control" placeholder="User Name"&gt;
                &lt;span class="help-block" *ngIf="userName.errors?.required &amp;&amp; userName.touched"&gt;
                  User Name is required
                &lt;/span&gt;
              &lt;/div&gt;
              &lt;div class="form-group" [class.has-error]="email.invalid &amp;&amp; email.touched" [class.has-success]="email.valid"&gt;
                &lt;input type="text" required [email]="user.email !== ''" [(ngModel)]="user.email" name="email" class="form-control" placeholder="Email"
                  #email="ngModel"&gt;
                &lt;span class="help-block" *ngIf="email.errors?.required &amp;&amp; email.touched"&gt;
                  Email is required
                &lt;/span&gt;
                &lt;span class="help-block" *ngIf="email.errors?.email &amp;&amp; email.touched"&gt;
                  Email is invalid
                &lt;/span&gt;
              &lt;/div&gt;
              &lt;div class="form-group" [class.has-error]="password.invalid &amp;&amp; password.touched" [class.has-success]="password.valid"&gt;
                &lt;input type="password" [(ngModel)]="user.password" required class="form-control" name="password" placeholder="Password" #password="ngModel"&gt;
                &lt;span class="help-block" *ngIf="password.invalid &amp;&amp; password.touched"&gt;
                  Password is required
                &lt;/span&gt;
              &lt;/div&gt;
              &lt;div class="form-group" [class.has-error]="confirmPasswordControl.invalid &amp;&amp; confirmPasswordControl.touched" [class.has-success]="confirmPasswordControl.valid"&gt;
                &lt;input type="password" required class="form-control" name="confirmPassword" placeholder="Confirm Password" [(ngModel)]="confirmPassword"
                  #confirmPasswordControl="ngModel"&gt;
                &lt;span class="help-block" *ngIf="confirmPasswordControl.errors?.required &amp;&amp; confirmPasswordControl.touched"&gt;
                  Confirm password is required
                &lt;/span&gt;
              &lt;/div&gt;
              &lt;div&gt;
                &lt;button class="btn btn-primary btn-block" type="submit" [disabled]="regsiterForm.invalid"&gt;Signup&lt;/button&gt;
              &lt;/div&gt;
            &lt;/div&gt;
          &lt;/form&gt;
        &lt;/mat-card-content&gt;
      &lt;/mat-card&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;</pre>
<p>For email validation, we have given an additional attribute and set the condition as [email]=&#8221;user.email !== &#8221;&#8221;, this is for not showing both the required validation and email validation together. This will show the required message if the user touched the field and not giving any values, and the email validation will get fired only if the entered value is not a valid email. Sounds good?</p>
<p><a href="https://sibeeshpassion.com/wp-content/uploads/2018/04/Template-Driven-Form-Validations.jpg"><img decoding="async" class="alignnone size-full wp-image-12800" src="https://sibeeshpassion.com/wp-content/uploads/2018/04/Template-Driven-Form-Validations.jpg" alt="" width="476" height="601" srcset="/wp-content/uploads/2018/04/Template-Driven-Form-Validations.jpg 283w, /wp-content/uploads/2018/04/Template-Driven-Form-Validations-238x300.jpg 238w, /wp-content/uploads/2018/04/Template-Driven-Form-Validations-400x505.jpg 400w, /wp-content/uploads/2018/04/Template-Driven-Form-Validations-475x600.jpg 475w" sizes="(max-width: 476px) 100vw, 476px" /></a></p>
<h3>Add register function</h3>
<p>Finally, let&#8217;s add our function register.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { OnInit, Component } from "@angular/core";
import { User } from '../models/user.model';
@Component({
  selector: 'app-registration',
  templateUrl: './registration.component.html',
  styleUrls: ['./registration.component.css']
})
export class RegistrationComponent implements OnInit {
  user = new User();
  constructor() {
  }

  ngOnInit() {
  }

  register(user: User): void{
    console.log(user);
  }
}


</pre>
<p>Once it is done, let&#8217;s open our browser console and see the data.</p>
<p><a href="https://sibeeshpassion.com/wp-content/uploads/2018/04/Console-output.jpg"><img decoding="async" class="alignnone size-full wp-image-12801" src="https://sibeeshpassion.com/wp-content/uploads/2018/04/Console-output.jpg" alt="" width="415" height="245" srcset="/wp-content/uploads/2018/04/Console-output.jpg 415w, /wp-content/uploads/2018/04/Console-output-300x177.jpg 300w, /wp-content/uploads/2018/04/Console-output-400x236.jpg 400w" sizes="(max-width: 415px) 100vw, 415px" /></a></p>
<p>Here we have seen how we can implement validation using template driven form. I will write my next article about implementing custom validators using directives in Angular, for comparing our password and confirm password field. Till then, bye.</p>
<h2><span id="conclusion">Conclusion</span></h2>
<p>Thanks a lot for reading. Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<h2><span id="your-turn-what-do-you-think">Your turn. What do you think?</span></h2>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/validation-using-template-driven-forms-in-angular-5/feed/</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Implement Shared Custom Validator Directive in Angular</title>
		<link>https://sibeeshpassion.com/implement-shared-custom-validator-directive-in-angular/</link>
					<comments>https://sibeeshpassion.com/implement-shared-custom-validator-directive-in-angular/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Sun, 22 Apr 2018 15:21:33 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[How to]]></category>
		<category><![CDATA[Angular 5]]></category>
		<category><![CDATA[Angular 5 Validations]]></category>
		<category><![CDATA[Angular directives]]></category>
		<category><![CDATA[Angular Shared Directive]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=12804</guid>

					<description><![CDATA[[toc] Introduction In this post, we are going to see how to create a custom validator directive in Angular 5. We have already seen how to do validation in our previous posts, and we have not done any validations for comparing the password and confirm the password, remember? Here we are going to see that. At the end of this article, you will get to know how to create a new shared directive according to our requirements. This post is a continuation of the course Developing an Angular 5 App series if you haven&#8217;t gone through the previous posts yet, [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h2>Introduction</h2>
<p>In this post, we are going to see how to create a custom validator directive in <a href="http://sibeeshpassion.com/category/client-side-technologies/angular/">Angular</a> 5. We have already seen how to do validation in our previous posts, and we have not done any validations for comparing the password and confirm the password, remember? Here we are going to see that. At the end of this article, you will get to know how to create a new shared directive according to our requirements<em>.</em> This post is a continuation of the course <em>Developing an Angular 5 App</em> series if you haven&#8217;t gone through the previous posts yet, I strongly recommend you to do that. You can find the links to the previous posts below. I hope you will like this article.</p>
<h2><em>Developing an Angular 5 App</em> series</h2>
<p>These are the previous posts in this series. Please go ahead and have a look.</p>
<ol>
<li><a href="http://sibeeshpassion.com/what-is-new-and-how-to-set-up-our-first-angular-5-application/">What Is New and How to Set Up our First Angular 5 Application</a></li>
<li><a href="http://sibeeshpassion.com/angular-5-basic-demo-project-overview/">Angular 5 Basic Demo Project Overview</a></li>
<li><a href="http://sibeeshpassion.com/generating-your-first-components-and-modules-in-angular-5-app/">Generating Your First Components And Modules in Angular 5 App</a></li>
<li><a href="http://sibeeshpassion.com/implement-validations-in-angular-5-app/">Implement Validations in Angular 5 App</a></li>
<li>Validation Using Template Driven Forms in Angular 5</li>
</ol>
<h2><span id="source-code">Source Code</span></h2>
<p>You can always clone or download the source code <a href="https://github.com/SibeeshVenu/ng5">here</a></p>
<h2>Background</h2>
<p>Validations have a vital role in all application no matter in what language it is been developed. And since it is an essential part, there are many ways to achieve it. If we create a custom shared directive for creating a compare validator, it would be a great piece of code right, which can be reused.</p>
<h2>Using the code</h2>
<p style="text-align: left;">It is recommended to clone the project from GitHub, so that you can try everything your own. Let&#8217;s go ahead and write some codes now.</p>
<h3>Creating a custom directive</h3>
<p>Let&#8217;s just create a new directive in a shared folder and name it <em>equal.validator.directive.ts. </em>Now open that file and start writing the code. Let&#8217;s import some of the core components first.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { Validator, AbstractControl, NG_VALIDATORS } from "@angular/forms";
import { Directive, Input } from "@angular/core";</pre>
<p>Now Let&#8217;s define our class and @Directive.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { Validator, AbstractControl, NG_VALIDATORS } from "@angular/forms";
import { Directive, Input } from "@angular/core";

@Directive({
    selector: "[appEqualValidator]",
    providers: [{
        provide: NG_VALIDATORS,
        useExisting: EqualValidatorDirective,
        multi: true
    }]
})
export class EqualValidatorDirective implements Validator {
    validate(c: AbstractControl): { [key: string]: any; } {
        throw new Error("Method not implemented.");
    }
    registerOnValidatorChange?(fn: () =&gt; void): void {
        throw new Error("Method not implemented.");
    }
}</pre>
<p>As you can see that, we are actually inheriting our new class  EqualValidatorDirective from Validator. Now we need to change the implementations of the method inside it. We should also add our new directive in app.module.ts file.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule} from '@angular/platform-browser/animations'
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { MatButtonModule, MatCardModule, MatInputModule, MatSnackBarModule, MatToolbarModule } from '@angular/material';
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { EqualValidatorDirective } from './shared/equal.validator.directive';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { NavComponent } from './nav/nav.component';
import { RegistrationComponent } from './registration/registration.component';
import { LoginComponent } from './login/login.component';

import { AuthService } from './auth.service';
import { AuthGuard } from './auth.guard';

const myRoots: Routes = [
  { path: '', component: HomeComponent, pathMatch: 'full' , canActivate: [AuthGuard]},
  { path: 'register', component: RegistrationComponent },
  { path: 'login', component: LoginComponent},
  { path: 'home', component: HomeComponent, canActivate: [AuthGuard]}
];

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    NavComponent,
    RegistrationComponent,
    LoginComponent,
    EqualValidatorDirective
  ],
  imports: [
    BrowserModule, BrowserAnimationsModule, FormsModule, ReactiveFormsModule,
    MatButtonModule, MatCardModule, MatInputModule, MatSnackBarModule, MatToolbarModule,
    RouterModule.forRoot(myRoots)
  ],
  providers: [AuthService, AuthGuard],
  bootstrap: [AppComponent]
})
export class AppModule { }
</pre>
<p>&nbsp;</p>
<h3>Implement validate</h3>
<p>Before we do that, we should add our new cutom directive selector in our confirm password field, because that&#8217;s where we are going to use our validator. So we are going to change our markup for confirm password field as below.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">&lt;div class="form-group" [class.has-error]="confirmPasswordControl.invalid &amp;&amp; confirmPasswordControl.touched" [class.has-success]="confirmPasswordControl.valid"&gt;
    &lt;input type="password" required class="form-control" name="confirmPassword" appEqualValidator="password" placeholder="Confirm Password" [(ngModel)]="confirmPassword" #confirmPasswordControl="ngModel"&gt;
    &lt;span class="help-block" *ngIf="confirmPasswordControl.errors?.required &amp;&amp; confirmPasswordControl.touched"&gt;
                  Confirm password is required
                &lt;/span&gt;
&lt;/div&gt;</pre>
<p>As you can see, we are using the selector  <em>appEqualValidator=&#8221;password&#8221; </em>in our confirm password field. Please do check my previous posts if you are not sure how to implement other validations like email and required.</p>
<p>Now let&#8217;s go back to our custom directive and make some changes.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">export class EqualValidatorDirective implements Validator {
    @Input() appEqualValidator: string;
    validate(c: AbstractControl): { [key: string]: any; } {
        const controlToCompare = c.parent.get(this.appEqualValidator)
        if (controlToCompare &amp;&amp; controlToCompare.value == c.value)return { "equal": true };
        return { "notEqual": true }
    }
    registerOnValidatorChange?(fn: () =&gt; void): void {
        throw new Error("Method not implemented.");
    }
}</pre>
<p>Here, we get our confirmPassword control in the absolute control &#8220;c&#8221;, and in the next line, we are just finding our password control by getting the parent element of confirmPassword. Once we get that, we can easily perform the comparison easily right? So, if it matches we return  { &#8220;equal&#8221;: true }; or else { &#8220;notEqual&#8221;: true }. Sounds good?</p>
<h3>Introduce new span for custom message</h3>
<p>Now we have a custom validator which compares two values, and the only thing which pending is, that to create a span for showing our new message in UI. Let&#8217;s change our markup now.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;div class="form-group" [class.has-error]="confirmPasswordControl.invalid &amp;&amp; confirmPasswordControl.touched" [class.has-success]="confirmPasswordControl.valid"&gt;
    &lt;input type="password" required class="form-control" name="confirmPassword" appEqualValidator="password" placeholder="Confirm Password" [(ngModel)]="confirmPassword" #confirmPasswordControl="ngModel"&gt;
    &lt;span class="help-block" *ngIf="confirmPasswordControl.errors?.required &amp;&amp; confirmPasswordControl.touched"&gt;
                  Confirm password is required
                &lt;/span&gt;
    &lt;span class="help-block" *ngIf="confirmPasswordControl.errors?.notEqual 
                      &amp;&amp; confirmPasswordControl.touched &amp;&amp; !confirmPasswordControl.errors?.required"&gt;
                  Password doesn't match
                &lt;/span&gt;
&lt;/div&gt;</pre>
<p>As you can see, we are showing the custom message only if the directive returns notEqual property and there are no required errors. Let&#8217;s run our application and see it in action.</p>
<p><a href="https://sibeeshpassion.com/wp-content/uploads/2018/04/Custom-Shared-Equal-Validator-Directive.jpg"><img decoding="async" class="alignnone size-full wp-image-12805" src="https://sibeeshpassion.com/wp-content/uploads/2018/04/Custom-Shared-Equal-Validator-Directive.jpg" alt="" width="384" height="529" srcset="/wp-content/uploads/2018/04/Custom-Shared-Equal-Validator-Directive.jpg 259w, /wp-content/uploads/2018/04/Custom-Shared-Equal-Validator-Directive-218x300.jpg 218w" sizes="(max-width: 384px) 100vw, 384px" /></a></p>
<p>&nbsp;</p>
<p>Here we have seen how we can implement shared custom validator directive. Let&#8217;s connect to a database and save these values in next article. Till then, bye.</p>
<h2><span id="conclusion">Conclusion</span></h2>
<p>Thanks a lot for reading. Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<h2><span id="your-turn-what-do-you-think">Your turn. What do you think?</span></h2>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/implement-shared-custom-validator-directive-in-angular/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Implementing Guard in Angular 5 App</title>
		<link>https://sibeeshpassion.com/implementing-guard-in-angular-5-app/</link>
					<comments>https://sibeeshpassion.com/implementing-guard-in-angular-5-app/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Mon, 26 Mar 2018 09:43:05 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[Angular 5]]></category>
		<category><![CDATA[Angular Auth Guard]]></category>
		<category><![CDATA[Angular Service]]></category>
		<category><![CDATA[Guard in Angular]]></category>
		<category><![CDATA[Implement Login in Angular]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=12742</guid>

					<description><![CDATA[[toc] Introduction This post is a continuation of the course Developing an Angular 5 App series if you haven&#8217;t gone through the previous posts yet, I strongly recommend you to do that. You can find the links to the previous posts below. In this post, we are going to implement Guard, which help us to restrict users to access some pages if they haven&#8217;t logged in to our application, in  Angular 5. So at the end of this article, you will get to know how you can handle unauthorized route accesses. I hope you will like this article. Developing an [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h2>Introduction</h2>
<p>This post is a continuation of the course <em>Developing an Angular 5 App</em> series if you haven&#8217;t gone through the previous posts yet, I strongly recommend you to do that. You can find the links to the previous posts below. In this post, we are going to implement Guard, which help us to restrict users to access some pages if they haven&#8217;t logged in to our application, in  <a href="http://sibeeshpassion.com/category/client-side-technologies/angular/">Angular</a> 5. So at the end of this article, you will get to know how you can handle unauthorized route accesses. I hope you will like this article.</p>
<h2><em>Developing an Angular 5 App</em> series</h2>
<p>These are the previous posts in this series. Please go ahead and have a look.</p>
<ol>
<li><a href="http://sibeeshpassion.com/what-is-new-and-how-to-set-up-our-first-angular-5-application/">What Is New and How to Set Up our First Angular 5 Application</a></li>
<li><a href="http://sibeeshpassion.com/angular-5-basic-demo-project-overview/">Angular 5 Basic Demo Project Overview</a></li>
<li><a href="http://sibeeshpassion.com/generating-your-first-components-and-modules-in-angular-5-app/">Generating Your First Components And Modules in Angular 5 App</a></li>
<li><a href="http://sibeeshpassion.com/implement-validations-in-angular-5-app/">Implement Validations in Angular 5 App</a></li>
<li><a href="http://sibeeshpassion.com/implementing-guard-in-angular-5-app">Implementing Guard in Angular 5 App</a></li>
</ol>
<h2><span id="source-code">Source Code</span></h2>
<p>You can always clone or download the source code <a href="https://github.com/SibeeshVenu/ng5">here</a></p>
<h2>Background</h2>
<p>We may be having many numbers of pages on our app, some may be used by logged in users, and some can be used by unauthorized users. But if you are letting all the users use all the pages, no matter whether they have logged in or not? Yeah, obviously that&#8217;s not a perfect application. In our application, we are going to make our homepage available only for a logged in user. To do this, we can use Guard.</p>
<h2>Using the code</h2>
<p style="text-align: left;">Let&#8217;s go ahead and write some codes now.</p>
<h3>Generate Guard</h3>
<p>As we are using Angular CLI, we can easily generate Auth Guard on our application. Do you remember that we have created some components in our previous article? We can always create a Guard in the same way.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">PS F:\Visual Studio\ng5&gt; ng generate guard auth</pre>
<p>In the above step, we are generating guard on our root level. Once you run the above command, this will generate two new Typescript files as follows.</p>
<p><a href="http://sibeeshpassion.com/wp-content/uploads/2018/03/Auth-Guard-in-Angular5.jpg"><img decoding="async" class="alignnone wp-image-12743 size-large" src="http://sibeeshpassion.com/wp-content/uploads/2018/03/Auth-Guard-in-Angular5-1024x410.jpg" alt="" width="1024" height="410" srcset="/wp-content/uploads/2018/03/Auth-Guard-in-Angular5-1024x410.jpg 1024w, /wp-content/uploads/2018/03/Auth-Guard-in-Angular5-300x120.jpg 300w, /wp-content/uploads/2018/03/Auth-Guard-in-Angular5-768x307.jpg 768w, /wp-content/uploads/2018/03/Auth-Guard-in-Angular5-400x160.jpg 400w, /wp-content/uploads/2018/03/Auth-Guard-in-Angular5.jpg 634w" sizes="(max-width: 1024px) 100vw, 1024px" /></a></p>
<p>Let&#8217;s go to those two files now.</p>
<p><strong>auth.guard.ts</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable&lt;boolean&gt; | Promise&lt;boolean&gt; | boolean {
    return true;
  }
}
</pre>
<p><strong>auth.guard.spec.ts</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { TestBed, async, inject } from '@angular/core/testing';

import { AuthGuard } from './auth.guard';

describe('AuthGuard', () =&gt; {
  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      providers: [AuthGuard]
    });
  });

  it('should ...', inject([AuthGuard], (guard: AuthGuard) =&gt; {
    expect(guard).toBeTruthy();
  }));
});
</pre>
<p>This is just a test file, we can see how to perform tests on the Angular app in another article. Let&#8217;s concentrate on the implementation for now.</p>
<h3>Generate login component and set up</h3>
<p>Now that we have Guard ready for modification before we do that, let&#8217;s create a component for login.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">PS F:\Visual Studio\ng5&gt; ng g c login
  create src/app/login/login.component.html (24 bytes)
  create src/app/login/login.component.spec.ts (621 bytes)
  create src/app/login/login.component.ts (265 bytes)
  create src/app/login/login.component.css (0 bytes)
  update src/app/app.module.ts (1331 bytes)
PS F:\Visual Studio\ng5&gt;</pre>
<p>Now it is time to edit our routes in app.module.ts with the new route for login. Please be noted that it is not a recommended way to create routes in app.module.ts file. We should create a separate routing module for the same and use it in app.module.ts. I will be sharing how to do that in another article.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { LoginComponent } from './login/login.component';

const myRoots: Routes = [
  { path: '', component: HomeComponent, pathMatch: 'full' },
  { path: 'register', component: RegistrationComponent },
  { path: 'login', component: LoginComponent},
  { path: 'home', component: HomeComponent}]

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    NavComponent,
    RegistrationComponent,
    LoginComponent
  ],
  imports: [
    BrowserModule, BrowserAnimationsModule, FormsModule, ReactiveFormsModule,
    MatButtonModule, MatCardModule, MatInputModule, MatSnackBarModule, MatToolbarModule,
    RouterModule.forRoot(myRoots)
  ],
  providers: [],
  bootstrap: [AppComponent]
})</pre>
<p>We may also need to edit the nav.component.html by adding a new button for login.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;mat-toolbar color="primary"&gt;
  &lt;button mat-button routerLink="/"&gt;Home&lt;/button&gt;
  &lt;button mat-button routerLink="/register"&gt;Register&lt;/button&gt;
  &lt;button mat-button routerLink="/login"&gt;Login&lt;/button&gt;
&lt;/mat-toolbar&gt;</pre>
<p>Now, go to your login.component.html file and add the following markup.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;mat-card&gt;
  &lt;form [formGroup]="form" (ngSubmit)="login()"&gt;
    &lt;mat-input-container&gt;
      &lt;input matInput type="email" placeholder="Email" formControlName="email" /&gt;
    &lt;/mat-input-container&gt;
    &lt;mat-input-container&gt;
      &lt;input matInput type="password" placeholder="Password" formControlName="password" /&gt;
    &lt;/mat-input-container&gt;
    &lt;button mat-raised-button type="submit" color="primary"&gt;Login&lt;/button&gt;
  &lt;/form&gt;
&lt;/mat-card&gt;</pre>
<p>As you can see, we are actually calling a login method on submit. Before we implement that function now on login.component.ts file let&#8217;s create an auth service and edit as preceding.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { Injectable } from '@angular/core';
import { Router } from '@angular/router';

@Injectable()
export class AuthService {

  constructor(private myRoute: Router) { }

  sendToken(token: string) {
    localStorage.setItem("LoggedInUser", token)
  }

  getToken() {
    return localStorage.getItem("LoggedInUser")
  }

  isLoggednIn() {
    return this.getToken() !== null;
  }

  logout() {
    localStorage.removeItem("LoggedInUser");
    this.myRoute.navigate(["login"]);
  }


}
</pre>
<p>Now it is time to edit our login.component.ts file.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  form;
  constructor(private fb: FormBuilder,
    private myRoute: Router,
    private auth: AuthService) {
    this.form = fb.group({
      email: ['', [Validators.required, Validators.email]],
      password: ['', Validators.required]
    });
  }

  ngOnInit() {
  }

  login() {
    if (this.form.valid) {
      this.auth.sendToken(this.form.value.email)
      this.myRoute.navigate(["home"]);
    }
  }

}
</pre>
<blockquote><p>This is not the preferred way of doing this, instead, you should create an API service and connect to a database. And then, check whether this email and password are valid or not, at last, you should set the localStorage with the token you get from server API. This topic is enough for another article, to make this article short, I am just setting the value email here.</p></blockquote>
<p>If you are getting an error as &#8220;ERROR Error: Uncaught (in promise): EmptyError: no elements in sequence&#8221;, please make sure that you have rxjs version greater than or equal to 5.5.4 in package.json file. The rxjs version 5.5.3 has this issue with Angular 5.</p>
<p>Now run your application and make sure that it is redirecting to the homepage. you can also check the localStorage entry on your browser console.</p>
<p><a href="http://sibeeshpassion.com/wp-content/uploads/2018/03/localStorage-entry.jpg"><img decoding="async" class="alignnone wp-image-12744 size-full" src="http://sibeeshpassion.com/wp-content/uploads/2018/03/localStorage-entry.jpg" alt="" width="612" height="356" srcset="/wp-content/uploads/2018/03/localStorage-entry.jpg 612w, /wp-content/uploads/2018/03/localStorage-entry-300x175.jpg 300w, /wp-content/uploads/2018/03/localStorage-entry-400x233.jpg 400w" sizes="(max-width: 612px) 100vw, 612px" /></a></p>
<h3>Set up Guard generated</h3>
<p>Let&#8217;s go to our auth.guard.ts file and make some changes.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { AuthService } from './auth.service';
import {Router} from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private auth: AuthService,
    private myRoute: Router){

  }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable&lt;boolean&gt; | Promise&lt;boolean&gt; | boolean {
    if(this.auth.isLoggednIn()){
      return true;
    }else{
      this.myRoute.navigate(["login"]);
      return false;
    }
  }
}
</pre>
<p>Do not forget to add AuthService and AuthGuard in providers in app.module.ts.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { AuthService } from './auth.service';
import { AuthGuard } from './auth.guard';</pre>
<h3>Use Auth Guard in Routes</h3>
<p>Wow, the set up is done, now it is time for action. Let&#8217;s go to our routes now and change the code as preceding.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">const myRoots: Routes = [
  { path: '', component: HomeComponent, pathMatch: 'full' , canActivate: [AuthGuard]},
  { path: 'register', component: RegistrationComponent },
  { path: 'login', component: LoginComponent},
  { path: 'home', component: HomeComponent, canActivate: [AuthGuard]}
];</pre>
<p>Run your application and try to access the home page before login if everything goes fine, it should redirect you to login page.</p>
<p><a href="http://sibeeshpassion.com/wp-content/uploads/2018/03/Guard-output.jpg"><img decoding="async" class="alignnone size-large wp-image-12746" src="http://sibeeshpassion.com/wp-content/uploads/2018/03/Guard-output-1024x453.jpg" alt="" width="1024" height="453" srcset="/wp-content/uploads/2018/03/Guard-output-1024x453.jpg 1024w, /wp-content/uploads/2018/03/Guard-output-300x133.jpg 300w, /wp-content/uploads/2018/03/Guard-output-768x339.jpg 768w, /wp-content/uploads/2018/03/Guard-output-400x177.jpg 400w, /wp-content/uploads/2018/03/Guard-output.jpg 634w" sizes="(max-width: 1024px) 100vw, 1024px" /></a></p>
<p>Let&#8217;s do some more coding on the nav.component.html and nav.component.ts for making our app more meaningful.</p>
<p><strong>nav.component.ts</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-nav',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.css']
})
export class NavComponent implements OnInit {

  constructor(private auth: AuthService) { }

  ngOnInit() {
  }

}
</pre>
<p><strong>nav.component.html</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">&lt;mat-toolbar color="primary"&gt;
  &lt;button mat-button routerLink="/home"&gt;Home&lt;/button&gt;
  &lt;button mat-button *ngIf="!auth.isLoggednIn()" routerLink="/register"&gt;Register&lt;/button&gt;
  &lt;button mat-button *ngIf="!auth.isLoggednIn()" routerLink="/login"&gt;Login&lt;/button&gt;
  &lt;button mat-button *ngIf="auth.isLoggednIn()" (click)="auth.logout()"&gt;Logout&lt;/button&gt;
&lt;/mat-toolbar&gt;</pre>
<p>Here we are just making the log out button available only for logged in users and hiding register and login button for logged in user. Sounds good? The auth.isLoggedIn function will be available on this page as we are injecting the auth service on out nav.component.ts file.</p>
<h2><span id="conclusion">Conclusion</span></h2>
<p>Thanks a lot for reading. Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<h2><span id="your-turn-what-do-you-think">Your turn. What do you think?</span></h2>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/implementing-guard-in-angular-5-app/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
	</channel>
</rss>
