<?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>javascript | Bogdan's blog</title>
	<atom:link href="https://blog.bogdancarpean.com/category/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.bogdancarpean.com</link>
	<description>Code and anything else.</description>
	<lastBuildDate>Mon, 01 Jun 2020 16:36:25 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.1.1</generator>

<image>
	<url>https://blog.bogdancarpean.com/wp-content/uploads/2022/12/icons8-pencil-drawing-96.png</url>
	<title>javascript | Bogdan's blog</title>
	<link>https://blog.bogdancarpean.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Javascript for of index</title>
		<link>https://blog.bogdancarpean.com/javascript-for-of-index/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=javascript-for-of-index</link>
					<comments>https://blog.bogdancarpean.com/javascript-for-of-index/#respond</comments>
		
		<dc:creator><![CDATA[Bogdan]]></dc:creator>
		<pubDate>Mon, 01 Jun 2020 16:36:25 +0000</pubDate>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[for of]]></category>
		<category><![CDATA[index]]></category>
		<category><![CDATA[iterable]]></category>
		<category><![CDATA[js]]></category>
		<guid isPermaLink="false">https://blog.bogdancarpean.com/?p=376</guid>

					<description><![CDATA[<p>Starting with ECMA 6 we have a new loop iterating statement in the form of for&#8230;of. This helps us to loop thru an iterable object (array, string, map, set&#8230;) in a simpler fashion than the classic for loop. To achieve this, we are going to use the entries() method of the Array: for (const [index, [&#8230;]</p>
The post <a href="https://blog.bogdancarpean.com/javascript-for-of-index/">Javascript for of index</a> first appeared on <a href="https://blog.bogdancarpean.com">Bogdan's blog</a>.]]></description>
										<content:encoded><![CDATA[<p>Starting with ECMA 6 we have a new loop iterating statement in the form of <strong>for&#8230;of</strong>. This helps us to loop thru an iterable object (array, string, map, set&#8230;) in a simpler fashion than the classic <strong>for</strong> loop.</p>
<p>To achieve this, we are going to use the <strong>entries()</strong> method of the Array:</p>
<pre>for (const [index, element] of myArray.entries()) {
  console.log(index, element)
}</pre>The post <a href="https://blog.bogdancarpean.com/javascript-for-of-index/">Javascript for of index</a> first appeared on <a href="https://blog.bogdancarpean.com">Bogdan's blog</a>.]]></content:encoded>
					
					<wfw:commentRss>https://blog.bogdancarpean.com/javascript-for-of-index/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>New ng lint syntax on Angular 6</title>
		<link>https://blog.bogdancarpean.com/new-ng-lint-syntax-on-angular-6/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=new-ng-lint-syntax-on-angular-6</link>
					<comments>https://blog.bogdancarpean.com/new-ng-lint-syntax-on-angular-6/#respond</comments>
		
		<dc:creator><![CDATA[Bogdan]]></dc:creator>
		<pubDate>Tue, 19 Jun 2018 22:50:36 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[Angular 2]]></category>
		<category><![CDATA[TypeScript]]></category>
		<category><![CDATA[angular]]></category>
		<category><![CDATA[angular/cli]]></category>
		<category><![CDATA[lint]]></category>
		<guid isPermaLink="false">http://blog.bogdancarpean.com/?p=251</guid>

					<description><![CDATA[<p>Let&#8217;s say you had a syntax like ng lint --format stylish on your package.json before Angular 6. Running this after you update to Angular 6 will result in the following error: Architect command with multiple targets cannot specify overrides. This error is not much of help when you know that before update the linting worked fine. For this [&#8230;]</p>
The post <a href="https://blog.bogdancarpean.com/new-ng-lint-syntax-on-angular-6/">New ng lint syntax on Angular 6</a> first appeared on <a href="https://blog.bogdancarpean.com">Bogdan's blog</a>.]]></description>
										<content:encoded><![CDATA[<div style="text-align: left;">Let&#8217;s say you had a syntax like <code>ng lint --format stylish</code> on your <code>package.json</code> before Angular 6.</div>
<p>Running this after you update to Angular 6 will result in the following error: <code>Architect command with multiple targets cannot specify overrides.</code> This error is not much of help when you know that before update the linting worked fine.</p>
<p>For this to work, we have to add the name of the application after the <code>ng lint</code> command: <code>ng lint your_app_name --format stylish</code></p>The post <a href="https://blog.bogdancarpean.com/new-ng-lint-syntax-on-angular-6/">New ng lint syntax on Angular 6</a> first appeared on <a href="https://blog.bogdancarpean.com">Bogdan's blog</a>.]]></content:encoded>
					
					<wfw:commentRss>https://blog.bogdancarpean.com/new-ng-lint-syntax-on-angular-6/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Deepcopy of JavaScript Objects and Arrays using lodash&#8217;s cloneDeep method</title>
		<link>https://blog.bogdancarpean.com/deepcopy-of-javascript-objects-and-arrays-using-lodashs-clonedeep-method/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=deepcopy-of-javascript-objects-and-arrays-using-lodashs-clonedeep-method</link>
					<comments>https://blog.bogdancarpean.com/deepcopy-of-javascript-objects-and-arrays-using-lodashs-clonedeep-method/#respond</comments>
		
		<dc:creator><![CDATA[Bogdan]]></dc:creator>
		<pubDate>Fri, 12 Jan 2018 14:08:06 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[angular]]></category>
		<category><![CDATA[cloneDeep]]></category>
		<category><![CDATA[copy objects]]></category>
		<category><![CDATA[deep clone]]></category>
		<category><![CDATA[deep copy]]></category>
		<category><![CDATA[lodash]]></category>
		<guid isPermaLink="false">http://blog.bogdancarpean.com/?p=182</guid>

					<description><![CDATA[<p>While developing JavaScript applications, often we need to make copies of Objects or Arrays containing Objects. Then we want to work with those copies without affecting the original objects. In a common scenario, we are going to deal with a simple, one level Object (an Object without other Objects nested inside), like in the following [&#8230;]</p>
The post <a href="https://blog.bogdancarpean.com/deepcopy-of-javascript-objects-and-arrays-using-lodashs-clonedeep-method/">Deepcopy of JavaScript Objects and Arrays using lodash’s cloneDeep method</a> first appeared on <a href="https://blog.bogdancarpean.com">Bogdan's blog</a>.]]></description>
										<content:encoded><![CDATA[<div style="position: relative;">While developing JavaScript applications, often we need to make copies of Objects or Arrays containing Objects. Then we want to work with those copies without affecting the original objects.<br />
In a common scenario, we are going to deal with a simple, one level Object (an Object without other Objects nested inside), like in the following example:</div>
<pre class="EnlighterJSRAW" data-enlighter-language="js">let originalObject = {name: 'Bunt', type: 'dog'};</pre>
<p>Then, we want to make a copy of the <code>originalObject</code>. In <code>ES6</code>, we are going to do something like this:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">let copiedObject = Object.assign({}, originalObject);</pre>
<p>This will create the <code>copiedObject</code> with all the properties and respective values of the <code>originalObject</code>. Now, if we want to change a value in the <code>copiedObject</code>, this will not change also the value into the <code>originalObject:</code></p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">copiedObject.type = 'cat';

console.log(originalObject.type); // will print 'dog'
console.log(copiedObject.type); // will print 'cat'</pre>
<p>Now, what is going to happen if we have a nested Object inside our Object, doing the same operations?</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">let originalObject = {name: 'Bunt', details: {type: 'dog', color: 'brown'}};

let copiedObject = Object.assign({}, originalObject);

copiedObject.details.type = 'cat'; 

console.log(originalObject.details.type); // will print 'cat' 
console.log(copiedObject.details.type); // will print 'cat'</pre>
<p>As you can see, when you change the value of a property in the nested Object of <code>copiedObject</code>, that change is perpetuated to the same property of the nested Object in <code>originalObject</code>. You&#8217;ll ask why that happened? Because JavaScript passes the primitive values (string, number, etc.) as <code>value-copy</code> and the compound values (Objects, Arrays, Functions) as <code>reference-copy</code> to the value of the primitives on that Object. This way, when we copied the Object containing the nested Object, we have created a <code>shallow copy</code> of that object, meaning that the primitives found at the first level of the Object have values that are copied, thus when we change them into the <code>copiedObject</code>, they are not going to change in the <code>originalObject</code> while all other property found in a nested object will have the value passed as a <code>reference</code> to the same property value into the nested Object of <code>originalObject</code>, thus when we change its value, we actually change the value of the reference, resulting on both nested Objects having the modified property value.</p>
<p>Now, what&#8217;s the solution to <code>deep copy</code> an Object or Array, meaning that we want to have a copy free of references at all nested levels so we can change the values inside without the fear of breaking the original?</p>
<p>The first solution you are going to find is to serialize the Object to a JSON, then parse back that JSON to a JavaScript Object, practically passing the Object thru a string that will clean up the Object tree from the references nested inside by recreating a new Object with copied properties and values from the original one.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">let copiedObject = JSON.parse(JSON.stringify(originalObject));</pre>
<p>But this is a controversial solution. Why? Because this is going to work fine as long as your Objects and the nested Objects only contains primitives, but if you have objects containing <code>functions</code>, this won&#8217;t work. Neither for <code>Date</code>.</p>
<p>So, what&#8217;s the working solution? We are going to use <a href="https://lodash.com/">lodash&#8217;s</a> <a href="https://lodash.com/docs/4.17.4#cloneDeep">cloneDeep</a> method to <code>deep copy</code> the Object. Lodash is an excellent JavaScript utility library for those not knowing it yet. The <code>cloneDeep</code> method will iterate all levels of the original Object and recursively copying all properties found.</p>
<p>The example I will give here is in Angular. Since we don&#8217;t want to carry all the bundle of <code>lodash</code> to the client, we are going only to import the cloneDeep method.</p>
<p>First, let&#8217;s install <code>lodash</code>into our project:</p>
<p><code>yarn add lodash</code> or <code>npm install lodash</code></p>
<p>Once installed, we are going to use in our component:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import * as cloneDeep from 'lodash/cloneDeep';

...

clonedObject = cloneDeep(originalObject);</pre>
<p>Importing <code>cloneDeep</code> will add to your build 18kb, a fair price to pay in order to have a reliable <code>deep copy</code> solution for you Objects.</p>
<p>I added a demo app on Github <a href="https://github.com/bogdancar/demo-angular-object-deep-copy">here</a>.</p>
<p><em>Interested in Angular? Join our <a href="https://www.meetup.com/Angular-Montreal/">Angular Montreal Meetup</a>.</em></p>The post <a href="https://blog.bogdancarpean.com/deepcopy-of-javascript-objects-and-arrays-using-lodashs-clonedeep-method/">Deepcopy of JavaScript Objects and Arrays using lodash’s cloneDeep method</a> first appeared on <a href="https://blog.bogdancarpean.com">Bogdan's blog</a>.]]></content:encoded>
					
					<wfw:commentRss>https://blog.bogdancarpean.com/deepcopy-of-javascript-objects-and-arrays-using-lodashs-clonedeep-method/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to run Angular tests on CI Docker Container with Chrome</title>
		<link>https://blog.bogdancarpean.com/how-to-run-angular-tests-on-ci-docker-container-with-chrome/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-run-angular-tests-on-ci-docker-container-with-chrome</link>
					<comments>https://blog.bogdancarpean.com/how-to-run-angular-tests-on-ci-docker-container-with-chrome/#respond</comments>
		
		<dc:creator><![CDATA[Bogdan]]></dc:creator>
		<pubDate>Sat, 06 Jan 2018 05:31:33 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[Continuous Integration]]></category>
		<category><![CDATA[angular]]></category>
		<category><![CDATA[angular tests]]></category>
		<category><![CDATA[angular/cli]]></category>
		<category><![CDATA[atlassian bitbucket pipelines]]></category>
		<category><![CDATA[chrome]]></category>
		<category><![CDATA[continuous integration]]></category>
		<category><![CDATA[debian]]></category>
		<category><![CDATA[docker]]></category>
		<category><![CDATA[node]]></category>
		<guid isPermaLink="false">http://blog.bogdancarpean.com/?p=171</guid>

					<description><![CDATA[<p>In this article, we are going to learn how to run the tests of an Angular solution generated with @angular/cli into a Docker Container without changing any of the initial configuration generated by @angular/cli. This is very important in the context of Continuous Integration workflow when you want to run your tests as you commit [&#8230;]</p>
The post <a href="https://blog.bogdancarpean.com/how-to-run-angular-tests-on-ci-docker-container-with-chrome/">How to run Angular tests on CI Docker Container with Chrome</a> first appeared on <a href="https://blog.bogdancarpean.com">Bogdan's blog</a>.]]></description>
										<content:encoded><![CDATA[<div style="position: relative;">In this article, we are going to learn how to run the tests of an Angular solution generated with <a href="https://cli.angular.io/" target="_blank" rel="noopener noreferrer"><code>@angular/cli</code></a> into a Docker Container without changing any of the initial configuration generated by <a href="https://cli.angular.io/" target="_blank" rel="noopener noreferrer"><code>@angular/cli</code></a>. This is very important in the context of Continuous Integration workflow when you want to run your tests as you commit to the repo.</div>
<p>For this example I&#8217;m gonna use the <a href="https://bitbucket.org/product" target="_blank" rel="noopener noreferrer">Atlassian Bitbucket Pipelines</a> for continuous integration, but is not limited to it, you can use it in any other environment that is using a <a href="https://www.docker.com/" target="_blank" rel="noopener noreferrer">Docker Container</a>, like Bitbucket, to test and build your Angular app.</p>
<p>To be able to test the Angular solution generated with <a href="https://cli.angular.io/" target="_blank" rel="noopener noreferrer"><code>@angular/cli</code></a>, we need a <a href="https://www.docker.com/" target="_blank" rel="noopener noreferrer">Docker Container</a> with <a href="https://nodejs.org/en/" target="_blank" rel="noopener noreferrer">Node</a> to run <code>npm install</code> in order to install the dependencies and then we need an instance of <a href="https://www.google.com/chrome/browser/desktop/index.html" target="_blank" rel="noopener noreferrer"><code>chrome</code></a> to run the tests.</p>
<p>For this, we have two solutions. I prefer the first one in which we take the official Node Docker Container, for the time being, 6.9.4, we install the <code>chrome</code> browser, then run <code>npm install</code> to fetch the dependencies of the project, then finally run our tests.</p>
<p>For Atlassian Bitbucket Pipelines, we are going to use the following code in the commit <code>bitbucket-pipelines.yml</code> file:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="ini">image: node:6.9.4

pipelines:
  default:
    - step:
        caches:
          - node
        script:
          - apt-get update; apt-get install -y gettext-base;
          - echo 'deb http://dl.google.com/linux/chrome/deb/ stable main' &gt; /etc/apt/sources.list.d/chrome.list
          - wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -
          - set -x &amp;&amp; apt-get update &amp;&amp; apt-get install -y xvfb google-chrome-stable
          - wget -q -O /usr/bin/xvfb-chrome https://bitbucket.org/atlassian/docker-node-chrome-firefox/raw/ff180e2f16ea8639d4ca4a3abb0017ee23c2836c/scripts/xvfb-chrome
          - ln -sf /usr/bin/xvfb-chrome /usr/bin/google-chrome
          - chmod 755 /usr/bin/google-chrome
          - npm install
          - ./node_modules/@angular/cli/bin/ng -v
          - ./node_modules/@angular/cli/bin/ng test --watch=false</pre>
<p>Please take into consideration that this is the code for a <code>debian linux</code> machine inside the Docker Container, so you have to adapt if you have a different machine.</p>
<p>I said that this solution is my preferred one because I want to test my app against the newest <code>chrome</code> version and I achieve this by installing the latest on each commit I make.</p>
<p>The downside of this solution is that it has to fetch all the updates for the <code>linux</code> machine and install <code>chrome</code> and it will take between 2 and 3 minutes to accomplish so this can become costly if you have a time limit on your Bitbucket account.</p>
<p>The second solution is to take a container from <a href="https://hub.docker.com/" target="_blank" rel="noopener noreferrer">Docker Container Hub</a> containing already Node and Chrome and to run the code starting from <code>npm install</code>. This way you cut in half the runtime, but you are going to test against the version of <code>chrome</code> installed into the Docker Container.</p>
<p>Have fun!</p>The post <a href="https://blog.bogdancarpean.com/how-to-run-angular-tests-on-ci-docker-container-with-chrome/">How to run Angular tests on CI Docker Container with Chrome</a> first appeared on <a href="https://blog.bogdancarpean.com">Bogdan's blog</a>.]]></content:encoded>
					
					<wfw:commentRss>https://blog.bogdancarpean.com/how-to-run-angular-tests-on-ci-docker-container-with-chrome/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Angular Service Worker landed on @angular.cli 1.6</title>
		<link>https://blog.bogdancarpean.com/angular-service-worker-landed-on-angular-cli-1-6/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=angular-service-worker-landed-on-angular-cli-1-6</link>
					<comments>https://blog.bogdancarpean.com/angular-service-worker-landed-on-angular-cli-1-6/#respond</comments>
		
		<dc:creator><![CDATA[Bogdan]]></dc:creator>
		<pubDate>Wed, 27 Dec 2017 18:15:08 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[Angular 2]]></category>
		<category><![CDATA[TypeScript]]></category>
		<category><![CDATA[angular]]></category>
		<category><![CDATA[angular/cli]]></category>
		<category><![CDATA[progressive web apps]]></category>
		<category><![CDATA[service worker]]></category>
		<guid isPermaLink="false">http://blog.bogdancarpean.com/?p=124</guid>

					<description><![CDATA[<p>With Angular 5 version having implemented a new Service Worker customized for Angular apps and @angular/cli 1.6 building it into your Angular app, a further step towards Progressive Web Apps has been made. Why is this important? Progressive Web Apps (or PWA) are seen for many years now as the evolution of apps, bound to [&#8230;]</p>
The post <a href="https://blog.bogdancarpean.com/angular-service-worker-landed-on-angular-cli-1-6/">Angular Service Worker landed on @angular.cli 1.6</a> first appeared on <a href="https://blog.bogdancarpean.com">Bogdan's blog</a>.]]></description>
										<content:encoded><![CDATA[<div style="position: relative;">With Angular 5 version having implemented a new Service Worker customized for Angular apps and @angular/cli 1.6 building it into your Angular app, a further step towards Progressive Web Apps has been made.</div>
<p>Why is this important? Progressive Web Apps (or PWA) are seen for many years now as the evolution of apps, bound to replace the native mobile apps and offer the user a seamless experience (native-like) on mobile platforms. With the announcement of Service Worker API development on Webkit/Safari, the future of across the board support for Service Worker never looked better.</p>
<p><img decoding="async" loading="lazy" class="wp-image-165 size-full aligncenter" src="http://vps277782.vps.ovh.ca/wp-content/uploads/2017/12/CanIUse_ServiceWorker.png" alt="" width="750" height="394" srcset="https://blog.bogdancarpean.com/wp-content/uploads/2017/12/CanIUse_ServiceWorker.png 750w, https://blog.bogdancarpean.com/wp-content/uploads/2017/12/CanIUse_ServiceWorker-300x158.png 300w" sizes="(max-width: 750px) 100vw, 750px" /></p>
<p>What Service Worker is supposed to do? As a building part of a PWA, the Service Worker is a mandatory condition, because is the part of the application that is going to run in the background to handle application requests and caching, permitting the application to function while offline, thus having the native-like behavior.</p>
<p>As of @angular/cli version 1.6, you can create your Angular application containing the Angular Service Worker simply by passing the <code>--service-worker</code> flag when you create the app using the CLI:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">ng new yourappname --service-worker</pre>
<p>If you look now into the folder<code>/app</code>, you notice that a new file appeared,<code>ngsw-config</code> which is the configuration file for the added Angular Service Worker. Inside this file, you can decide which assets will be cached and in which manner.</p>
<p>Then, when you build your app, on the folder<code>/dist</code> you will see them <code>ngsw.json</code>and,<code>ngsw-worker.js</code> which is the actual Angular Service Worker.</p>
<p>More info on how to add the Angular Service Worker to your app <a href="https://medium.com/google-developer-experts/a-new-angular-service-worker-creating-automatic-progressive-web-apps-part-2-practice-3221471269a1" target="_blank" rel="noopener noreferrer">here</a>.</p>
<p>If you want to learn more about the Service Worker, <a href="https://developers.google.com/web/fundamentals/primers/service-workers/" target="_blank" rel="noopener noreferrer">here</a> is a good article.</p>The post <a href="https://blog.bogdancarpean.com/angular-service-worker-landed-on-angular-cli-1-6/">Angular Service Worker landed on @angular.cli 1.6</a> first appeared on <a href="https://blog.bogdancarpean.com">Bogdan's blog</a>.]]></content:encoded>
					
					<wfw:commentRss>https://blog.bogdancarpean.com/angular-service-worker-landed-on-angular-cli-1-6/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Angular how to dynamically inject a component to DOM</title>
		<link>https://blog.bogdancarpean.com/angular-how-to-dynamically-inject-a-component-to-dom/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=angular-how-to-dynamically-inject-a-component-to-dom</link>
					<comments>https://blog.bogdancarpean.com/angular-how-to-dynamically-inject-a-component-to-dom/#comments</comments>
		
		<dc:creator><![CDATA[Bogdan]]></dc:creator>
		<pubDate>Thu, 19 Oct 2017 03:42:28 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[Angular 2]]></category>
		<category><![CDATA[TypeScript]]></category>
		<category><![CDATA[add component]]></category>
		<category><![CDATA[angular]]></category>
		<category><![CDATA[Angular 4]]></category>
		<category><![CDATA[directive]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[inject component]]></category>
		<category><![CDATA[Typescript]]></category>
		<category><![CDATA[ViewContainerRef]]></category>
		<guid isPermaLink="false">http://blog.bogdancarpean.com/?p=114</guid>

					<description><![CDATA[<p>Note: given the semver adopted from now on by Angular team, I will refer to all versions of Angular2+ as Angular. For the old Angular 1.x, I will use AngularJs In this post, we&#8217;ll take a look on how to dynamically inject a component into the DOM using a directive as a placeholder and ViewContainerRef Angular class. For simplicity, we will declare a new [&#8230;]</p>
The post <a href="https://blog.bogdancarpean.com/angular-how-to-dynamically-inject-a-component-to-dom/">Angular how to dynamically inject a component to DOM</a> first appeared on <a href="https://blog.bogdancarpean.com">Bogdan's blog</a>.]]></description>
										<content:encoded><![CDATA[<p><strong>Note</strong>: <em>given the </em>semver<em> </em>adopted<em> from now on by </em>Angular<em> team, I will refer to all versions of Angular2+ as Angular. For the old Angular </em>1.x,<em> I will use AngularJs</em></p>
<p>In this post, we&#8217;ll take a look on how to dynamically inject a component into the DOM using a directive as a placeholder and ViewContainerRef Angular class.</p>
<p>For simplicity, we will declare a new Angular component that later will be dynamically added/removed to/from the DOM:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { Component } from '@angular/core';

@Component({
  selector: 'app-injected',
  templateUrl: `&lt;div&gt;Another component was added&lt;/div&gt;`,
  styleUrls: ['./injected.component.css']
})
export class InjectedComponent {

}</pre>
<p>Then we declare the directive used as a placeholder on the DOM where we want to inject the new component:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { Directive, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[appInject]'
})
export class InjectDirective {

  constructor(public viewContainerRef: ViewContainerRef) { }

}</pre>
<p>We add the directive on DOM in the place where the new component will be injected:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;div class="where_you_want_to_inject"&gt;    
  &lt;ng-template appInject&gt;&lt;/ng-template&gt;
&lt;/div&gt;</pre>
<p>Finally, into the parent component, we add two functions, one who add the component, other who remove it:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { Component, ViewChild, ComponentFactoryResolver } from '@angular/core';
import { InjectDirective } from '../inject.directive';
import { InjectedComponent } from '../injected/injected.component';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent {

  @ViewChild(InjectDirective) injectComp: InjectDirective;

  constructor(private _componentFactoryResolver: ComponentFactoryResolver) {
  }

  public addComp() {
    const componentFactory = this._componentFactoryResolver.resolveComponentFactory(InjectedComponent);
    const viewContainerRef = this.injectComp.viewContainerRef;
    const componentRef = viewContainerRef.createComponent(componentFactory);
  }

  public removeComp() {
    const componentFactory = this._componentFactoryResolver.resolveComponentFactory(InjectedComponent);
    const viewContainerRef = this.injectComp.viewContainerRef;
    const componentRef = viewContainerRef.remove();
  }

}</pre>
<p>This way we can dynamically add/remove components.</p>
<p>If you need an example, I added a working demo app on Github <a href="https://github.com/bogdancar/angular2-dynamically-add-component-to-dom" target="_blank" rel="noopener noreferrer">here</a>.</p>
<p>&nbsp;</p>
<p><em>If your company needs consulting on migration from Angular 1 to Angular 2/4/5 or training/update Angular knowledge, write me to <a href="mailto:contact@bogdancarpean.com">contact@bogdancarpean.com</a></em></p>The post <a href="https://blog.bogdancarpean.com/angular-how-to-dynamically-inject-a-component-to-dom/">Angular how to dynamically inject a component to DOM</a> first appeared on <a href="https://blog.bogdancarpean.com">Bogdan's blog</a>.]]></content:encoded>
					
					<wfw:commentRss>https://blog.bogdancarpean.com/angular-how-to-dynamically-inject-a-component-to-dom/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Angular.js share variables between controllers with service</title>
		<link>https://blog.bogdancarpean.com/angular-js-share-variables-between-controllers-with-service/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=angular-js-share-variables-between-controllers-with-service</link>
					<comments>https://blog.bogdancarpean.com/angular-js-share-variables-between-controllers-with-service/#respond</comments>
		
		<dc:creator><![CDATA[Bogdan]]></dc:creator>
		<pubDate>Wed, 10 May 2017 23:15:43 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[angular]]></category>
		<category><![CDATA[controller]]></category>
		<category><![CDATA[directive]]></category>
		<category><![CDATA[scope]]></category>
		<category><![CDATA[share variables]]></category>
		<guid isPermaLink="false">http://blog.bogdancarpean.com/?p=69</guid>

					<description><![CDATA[<p>Note: This article applies to Angular 1 and the example is written in ES5. Let&#8217;s say you have a directive where you have a button and once clicked you want an event to happen in another directive. The problem is that the two directives have different scopes, so passing the change directly is not possible. [&#8230;]</p>
The post <a href="https://blog.bogdancarpean.com/angular-js-share-variables-between-controllers-with-service/">Angular.js share variables between controllers with service</a> first appeared on <a href="https://blog.bogdancarpean.com">Bogdan's blog</a>.]]></description>
										<content:encoded><![CDATA[<p><em>Note: This article applies to Angular 1 and the example is written in ES5.</em></p>
<p>Let&#8217;s say you have a directive where you have a button and once clicked you want an event to happen in another directive. The problem is that the two directives have different scopes, so passing the change directly is not possible. In this approach, we are going to use a service to pass the data between the controllers of the two directives.</p>
<p>For example, we are going to take a directive that has a button that once clicked we display a custom modal. The modal is another directive not related to the one where the click originated.</p>
<p>First, we are going to write the service:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js" data-enlighter-title="dataService.js">"use strict";

angular.module("someApp").service("dataService", function () {

    var _isModalClicked  = false;

    this.setModalClicked = function(flag){
        _isModalClicked = flag;
    };

    this.getModalClicked = function(){
        return _isModalClicked;
    };
});</pre>
<p>Then, from the controller sending the change (the one attached to button directive), we are going to set the variable on the service (don&#8217;t forget to import the service into the controller):</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">...
$scope.buttonClick = function(ev){
    dataService.setModalClicked(true);
}
...

</pre>
<p>At this point, we have wired the controller to the service and changed the state of _isModalClicked to true. What is left is to listen to that change inside of the controller consuming the event and to propagate the change, leading to showing the modal. The consuming controller will look like this:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">'use strict';

angular.module('someApp')
    .controller('modalCtrl', function ($scope, dataService) {

        $scope.$watch(function() { return dataService.getModalClicked(); }, function(newVal) {
            $scope.showModal = newVal;
        }, true);
    });</pre>
<p>This way, you have a clear separation of concerns when you want to pass a variable change between scopes.</p>The post <a href="https://blog.bogdancarpean.com/angular-js-share-variables-between-controllers-with-service/">Angular.js share variables between controllers with service</a> first appeared on <a href="https://blog.bogdancarpean.com">Bogdan's blog</a>.]]></content:encoded>
					
					<wfw:commentRss>https://blog.bogdancarpean.com/angular-js-share-variables-between-controllers-with-service/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
