<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Mikael Araya blog - Medium]]></title>
        <description><![CDATA[Few code samples testing new tools and technologies - Medium]]></description>
        <link>https://medium.com/mikael-araya-blog?source=rss----32ee1f0de2f2---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Mikael Araya blog - Medium</title>
            <link>https://medium.com/mikael-araya-blog?source=rss----32ee1f0de2f2---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 22:58:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/mikael-araya-blog" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Developing Ethereum Smart Contract using ERC721 (non-fungible) Token Standard]]></title>
            <link>https://medium.com/mikael-araya-blog/developing-ethereum-smart-contract-using-erc721-non-fungible-token-standard-86f3974a631d?source=rss----32ee1f0de2f2---4</link>
            <guid isPermaLink="false">https://medium.com/p/86f3974a631d</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[erc721]]></category>
            <category><![CDATA[ethereum-blockchain]]></category>
            <category><![CDATA[fungible-tokens]]></category>
            <dc:creator><![CDATA[Mikael Araya]]></dc:creator>
            <pubDate>Tue, 24 Mar 2020 19:56:07 GMT</pubDate>
            <atom:updated>2023-05-18T15:09:14.973Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Aq82tW0D4c9Xn8zHRYecw.png" /></figure><p>In the following sections I’ll try to show you a basic implementation of a smart contract that utilizes a non-fungible ERC721 standard. Since we are going to be developing a smart contract I’m assuming you have a basic understanding of solidity and the Ethereum network in general.</p><p>For convenience purposes, you can use <a href="https://remix.ethereum.org/">remix IDE </a>to follow this tutorial to make the compilation and deployment process easy.</p><p>Before we jump on and start writing code lets have a basic introduction of what ERC721 token standard is and what it stands for. ERC-721 is a free, open standard that describes how to build non-fungible or unique tokens on the Ethereum blockchain. It outlines how a token is created, how ownership is transferred, how a token is destroyed etc…</p><p>instead of implementing ERC721 standard ourselves self we’ll leverage the <a href="https://github.com/OpenZeppelin/openzeppelin-contracts/tree/master/contracts/token/ERC721">openzeppelin ERC721 standard implementation</a>.</p><p>if you are interested to understand more about fungible and non-fungible token I recommend you refer to this <a href="https://medium.com/@brenn.a.hill/noobs-guide-to-understanding-erc-20-vs-erc-721-tokens-d7f5657a4ee7">blog</a>. Or if you want to explore more about each standard refer to this link for <a href="https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md">ERC20</a> and this for <a href="http://erc721.org/">ERC721</a> standard.</p><p>The smart contract we are going to develop to demonstrate the usage of ERC721 token is an Event smart contract that lets event organizers and event attendees do their business without any intermediaries.</p><p>It lets:</p><ul><li>Event organizers create an event</li><li>Event attendees to get tickets for events they want to attend</li><li>Attendees Transfer ticket to anyone they want after purchasing the ticket</li><li>Attendees Get a refund for canceled events</li><li>Authenticate themselves at the venue of the event on the event day</li><li>Organizers collect payment to sold tickets.</li></ul><p>The smart contract has a few business rules such as</p><ul><li>A user can only purchase a maximum of 5 tickets at once. this is to mitigate from DOS attach that could occur from an infinite loop. For more smart contract security concerns and mitigation strategies check out this <a href="https://consensys.github.io/smart-contract-best-practices/known_attacks">site</a>.</li><li>The only event organizer is allowed to cancel the event.</li><li>The event can only be canceled before it starts</li><li>Users can ask refund to their tickets only if the event has been canceled.</li><li>Payment collection can only be done by the event owner</li><li>Payment collection can only be done after the event has ended.</li></ul><p>We will enforce these rules inside the smart contract. Feel free to clone the <a href="https://github.com/Mikearaya/bionic_event_dapp.git">repository</a> and customize the contract to your needs.</p><p>Before writing any single line of code make sure you have a solidity compiler version greater than <strong>0.5.0 </strong>on your <a href="https://remix.ethereum.org/">remix IDE</a> or installed on your development environment.</p><p>As I mentioned earlier we are not going to implement the ERC721 standard interface our self instead use the <a href="https://github.com/OpenZeppelin/openzeppelin-contracts/tree/master/contracts/token/ERC721">openzepline</a> implementation of the interface to be exact we are going to use the <a href="https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721Full.sol">ERC721Full</a> implementation. I took it another step further and created a single file that consists of all the dependencies <a href="https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721Full.sol">ERC721Full</a> openzepline implementation has you can find it at this <a href="https://github.com/Mikearaya/bionic_event_dapp/blob/master/contracts/ERC721Full.sol">link</a>.</p><p>before we create our smart contract first create a file called <strong>ERC721Full.sol</strong> on the same directory as to where you will define the event smart contract and copy any paste the code <a href="https://github.com/Mikearaya/bionic_event_dapp/blob/master/contracts/ERC721Full.sol">here</a> into that file.</p><p>Now we are ready to create an <strong>event.sol</strong> file and define the event smart contract as follows.</p><pre>pragma solidity ^0.5.0;</pre><pre>contract Event {}</pre><p>Next let&#39;s define the state properties of the smart contract.</p><pre>string public name;<br>uint256 public startDate;<br>uint256 private ticketId;<br>uint256 public endDate;<br>uint256 public available;<br>string public location;<br>uint8 private MAX_PURCHASE = 5;<br>string public description;<br>bool private canceled;<br>uint public ticketPrice;<br>address payable public owner</pre><p>Also to make the transactions on our contract more traceable and <strong>auditable</strong> let&#39;s define a few events we will be using throughout the system</p><pre>event TicketPurchased(address purchaser, uint quanntity, uint date, address indexed indexedPurchased );<br>event TicketTransfered(address _from, address _to, uint _tokenId);<br>event PaymentCollected(address _event, address _organizer, uint _balance );<br>event TicketRefended(address _event, address _requestedBy, uint _ticketId, uint _ticketPrice);</pre><p>Now before we create a constructor function that initializes the contract state values at creation time. Let&#39;s inherit the ERC721Full class that implements the ERC721 standard. And extend our event class.</p><pre>import &quot;./ERC721Full.sol&quot;;</pre><pre>Class Event extends ERC721Full {<br>}</pre><p>now our event class will have all the public functions that ERC721 Full implements at its disposal. Next, create the constructor function that will initialize the properties of the event at creation time.</p><pre>constructor(address payable _organizer, <br>            string memory _name, <br>            uint _start,<br>            uint _end,<br>            string memory _description,<br>            string memory _location,<br>            uint supply,<br>            uint _ticketPrice <br>) ERC721Full(_name, “TKT”) public {</pre><pre>           name = _name;<br>           startDate = _start;<br>           endDate = _end;<br>           ticketPrice = _ticketPrice;<br>           available = supply;<br>           description = _description;<br>           owner = _organizer;<br>           location = _location;</pre><pre>}</pre><p>notice we have called the constructor of ERC721Full when we initialize the event contract and passed the name of event and the symbol, this will be used as the name for the token and symbol of the token respectively, when invoking this line</p><pre>constructor(....) ERC721Full(_name, “TKT”) public {}</pre><p>at this point if we just compiled and deployed out contract it will work but we have no way of accessing the value and manipulating it except the function defined by the ERC721 class. Lets now define functions that will be used to make this event a smart contract that implements the ERC721 token.</p><p>The first thing is first to let create a function that will allow event attendees to purchase a ticket.</p><pre>function purchaseTicket(uint quantity) public payable {<br>      <br>    require(quantity &lt;= MAX_PURCHASE, “can not purchase more than 5 ticket at once”);<br>    require(available &gt;= quantity, “not enough ticket quantity available!!!”);<br>    require(msg.value &gt;= ticketPrice.mul(quantity), “not enough money sent”);<br>    <br>     for(uint8 i = 0; i &lt; quantity; i++) {<br>           ticketId++;<br>           available — ;<br>           _mint(msg.sender,ticketId);<br>      }</pre><pre>     emit TicketPurchased(msg.sender, quantity, now, msg.sender);<br>}</pre><p>The <strong><em>purchaseTicket</em></strong> function takes a single argument, the number of tickets to be purchased. also, There are a couple of things happening to ensure the validity of input parameters from the user, let walk through each line by line</p><ul><li>The first line of code checks if the user is asking to purchase the ticket within the range of the maximum amount allowed to be purchased by the system contract.</li><li>The second line checks if there are available tickets equal to the required amount by the user.</li><li>The third line checks if the user has passed enough ether to purchase the ticket quantity they are requesting.</li></ul><p>If any of the above checks return false the execution of the code will be halted and control will return to whoever invoked the function with an exception. After all checks out the next thing left to do is generate the non-fungible ERC721 by calling the <strong><em>_mint</em></strong> internal function we inherited from ERC721 and passing it the token owner address and token/ticket id to mint a new token/ticket the _mint function will revert if the given token ID already exists. finally, we emitting <strong><em>TicketPurchased()</em></strong> event and log the <em>sender address, the quantity of ticket purchased, and the current timestamp </em>for future reference of this transaction. This can be used by the front-end using <strong><em>web3</em></strong> or any tool that provides access to the Ethereum network, but we will not get into that on this blog.</p><p>Let&#39;s create a second function that checks if the token we just created or any other token id belongs to a given address or not we will call this function <strong><em>isTicketValid</em></strong> for simplicity purpose :) that takes 2 arguments, <em>address of the owner &amp; tokenId</em> to be checked.</p><pre>function isTicketValid(address _owner, uint _tokenId) onlyOwner public returns(bool) {</pre><pre>if(ownerOf(_tokenId) == _owner) {<br>            _burn(_tokenId);<br>          return true;<br>       } else {<br>          return false;<br>       }<br>}</pre><ul><li>The first line of code checks the owner of the provided <em>tokenId</em> is equal to the owner&#39;s address passed to it. If that is true we make use of the other function we inherited from the ERC721Full <strong><em>_burn() </em></strong><em>which takes a single argument, the tokenId to destroy the token forever so that it will not be used it the future</em>. Else if it is not the owner we simply return false to the invoker indicating a negative result.</li></ul><p>One thing we also notice is that we have made use of a <em>modifier</em> <strong>onlyOwner</strong>. This modifier checks to see if the calling address or the invoker is the owner of the event and code execution continues if this modifier returns true. We have not defined this modifier yet so let&#39;s just do that now.</p><pre>modifier onlyOwner {<br>    require(msg.sender == owner, “only event owner is allowed to perform this action”);<br>    _;<br>}</pre><p>next, let&#39;s define a function that will let the event organizer cancel the event for whatever reason they might have. We will call it, you guessed it <strong><em>cancelEvent</em></strong></p><pre>function cancelEvent() onlyOwner public { <br>    require(now &gt; startDate, “can not cancel event after it has started”);<br>    canceled = true;<br>}</pre><p>If you notice closely you will see we have used the <strong>onlyOwner</strong> modifier on this function to restrict access to the event owner only. Next, we checked if the event has not started yet and if that’s true we set the boolean state value canceled to true.</p><p>You might ask what happens to the tickets if the owner decides to cancel the event after purchasing tickets. Well let&#39;s define a function that answers that question now, let&#39;s call it <strong><em>getRefund</em></strong>.</p><pre>function getRefund(uint ticket) public {<br>     require(address(0) != msg.sender, “invalid address provided”);<br>     require(canceled, “refund is only available for cacanceled events”); <br>     _burn(ticket);<br>     msg.sender.transfer(ticketPrice);<br>     emit TicketRefended(address(this), msg.sender, ticket, ticketPrice);</pre><pre>}</pre><p>As usual, we will do a check on the user inputs passed to the smart contract before executing code that will alter the state of the ledger.</p><ul><li>The first line of code checks if the address value of <strong><em>msg.sender</em></strong> is valid.</li><li>Next, we check if the event has been actually canceled because that is the only time a user can request a refund.</li><li>If the above checks returned true the remaining task is to <strong><em>_burn</em></strong> the ticket that is refunded so that it will not be used for the second time</li><li>Finally, the contract will <strong><em>transfer</em></strong> ether value equal to the ticket price back the address that requested it and emit the <strong><em>TicketRefunded</em></strong> event logging the <em>event contract address, requester address and ticketId </em>for future reference.</li></ul><p>To make things simple to invokers lets create a helper function that returns the value of is canceled to the invoker.</p><pre>function isCanceled() public view returns(bool) {<br>     return canceled;<br>}</pre><p>our event contract is finally coming together but there are few functionalities that remaining before we can deploy it to the network. As we mentioned at the start the event attendees can transfer tokens to whoever they want, so let&#39;s implement the function that will enable users to do just that. We will call it <strong><em>transferTicket</em></strong> that takes<em> the address of the recipient, and the tokenId</em> we want to transfer to that address.</p><pre>function transferTicket(address _to, uint _tokenId) public {<br>     require(address(0) != _to, “invalid address provided”);<br>     transferFrom(msg.sender, _to, _tokenId);<br>     emit TicketTransfered(msg.sender, _to, _tokenId);<br>}</pre><ul><li>First, we need to check if the address of the recipient is a valid address.</li><li>If the address is valid then all we have to do now is use the <strong><em>transferFrom</em></strong> function we inherited from ERC721Full which <em>Transfers the ownership of a given token ID to another address. Requires the </em><strong><em>msg.sender</em></strong><em> to be the owner, approved, or operator.</em></li><li>Finally, we log this transaction by emitting <strong>TicketTransfered</strong> event and logging <em>address of the token owner, address of the recipient and the tokenid</em>.</li></ul><p>Now the only function remaining before we can deploy this contract to the Ethereum network is <strong><em>collectPayment</em></strong> which will enable the event organizer to collect the payments received from selling tickets. So let&#39;s go ahead and define that.</p><pre>function collectPayment() onlyOwner public {<br>      require(now &gt; endDate &amp;&amp; !canceled, “can not collect payment before the event is over”);<br>      owner.transfer(address(this).balance);<br>      selfdestruct(msg.sender);<br>      <br>      emit PaymentCollected(address(this), msg.sender, address(this).balance );</pre><pre>}</pre><p>as usual, we are checking the validity of the inputs provided by the user and also the business rules that govern the contract. Also notice we have used the <strong><em>onlyOwner</em></strong> modifier to restrict access to the event organizer only. then we check to see the time of this if the event has ended by comparing the current timestamp with the event end date. If that checks out we <strong><em>transfer</em></strong> the balance held in the smart contract to the address of the owner followed by <strong><em>selfdistruct</em></strong> call of the smart contract destroying the event. Finally, we emit an event that logs this transaction called <strong><em>PaymentCollected</em></strong> and passing the <em>address of the contract, address of owner and balance of the contract</em> for future reference.</p><p>We are almost ready to compile this contract and deploy it to the network and start creating events but before that let&#39;s create one additional helper function that will give us the tokens owned by a specific user and call it <strong><em>getOwnerTicket</em>()</strong> which takes one argument <em>address we want to get the token from</em> and lock it with a modifier so as only the owner can call this function.</p><pre>function getOwnersTicket(address _owner) public view returns(uint[] memory) {<br>    return _tokensOfOwner(_owner);<br>}</pre><p><strong><em>getOwnersTicket</em></strong> make use of the ERC721 function <strong><em>_tokensOfOwner</em> </strong>we<strong> </strong>inherited <em>that takes address to return all the tokens owned by that address.</em></p><p>Now we can compile the contract and deploy it to the network so lets just do that. if you have followed me to this point line byline i don’t you will have any problem, but in case you face some issues contact me and i’ll try to help you.</p><p>Congratulation you have just created and deployed a non-fungible token successfully!!! :)</p><h4>Reference</h4><ul><li><a href="https://solidity.readthedocs.io/en/v0.5.14/">solidity documentation</a></li><li><a href="https://ethereum.org/developers/#other-tools">Ethereum documentation</a></li><li><a href="http://erc721.org/">ERC721</a></li><li>Alchemy’s <a href="https://znsrc.com/c/ehrzbwkvru">NFT Code Snippets and Templates</a> library</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86f3974a631d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mikael-araya-blog/developing-ethereum-smart-contract-using-erc721-non-fungible-token-standard-86f3974a631d">Developing Ethereum Smart Contract using ERC721 (non-fungible) Token Standard</a> was originally published in <a href="https://medium.com/mikael-araya-blog">Mikael Araya blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Snapshot Testing]]></title>
            <link>https://medium.com/mikael-araya-blog/snapshot-testing-6e78454aeeba?source=rss----32ee1f0de2f2---4</link>
            <guid isPermaLink="false">https://medium.com/p/6e78454aeeba</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[testing-framework]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[snapshot-testing]]></category>
            <dc:creator><![CDATA[Mikael Araya]]></dc:creator>
            <pubDate>Tue, 24 Mar 2020 19:50:36 GMT</pubDate>
            <atom:updated>2020-03-06T04:59:16.946Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A3YyM5VeE5Tutb3QKaaGhw.jpeg" /></figure><h3>Snapshot Testing: The Easiest way to test your code haven’t changed since last time</h3><p>Software testing is one of the important requirements when developing great quality software. testing gives us software developers the peace of mind of knowing all of the application features work as expected before delivering it to the client or after making a change to it.</p><p>During the year’s various types and levels of testing have been suggested to help guarantee applications work as expected. such as:</p><p><strong>Approaches</strong></p><ul><li>box testing</li><li>White-box testing</li><li>black-box testing</li><li>visual testing</li><li>grey-box testing</li><li>etc…</li></ul><p><strong>Levels</strong></p><ul><li><a href="https://jestjs.io/docs/en/snapshot-testing"><strong><em>Snapshot testing</em></strong></a></li><li>Unit testing</li><li>Integration testing</li><li>System testing</li><li>Operational acceptance testing</li><li>end-to-end testing</li><li>etc…</li></ul><p>In this article, our main focus is going to be the implementation of snapshot testing, but there are plenty of materials out there that describe each method in great detail, for starters you can use <a href="https://en.wikipedia.org/wiki/Software_testing">Wikipedia</a></p><p><strong>Prerequisites</strong></p><p>You don’t need any experience or knowledge of the tools mentioned to understand what snapshot testing is since I’ll try to show the output of each executed code alongside it. But if you want to follow along make sure you have the following tools and all their dependencies are installed on your workstation.</p><blockquote>all of the code in this article are developed and tested on ubuntu 19.04 so make sure to add all the required dependency if you are using different operating system</blockquote><ul><li><a href="https://reactjs.org/docs/getting-started.html">ReactJs</a> — basic knowledge of React or any similar framework will be helpful to understand the content more.</li><li><a href="https://jestjs.io/">Jestjs</a> — <a href="https://jestjs.io/">jest</a> is the tool we will be using to write the snapshot test.</li></ul><p><strong>Snapshot Testing</strong></p><p>Snapshot testing is one of the testing methodologies that help us ensure our code hasn’t changed or in the case it has changed lets us confirm if the change was intentional or not before it’s too late.</p><p>It can achieve this by saving/taking a snapshot of the rendered output the first time we run the test and comparing that output with tests we run after that and throw an error if the code has changed.</p><blockquote>snapshot files should be included inside our repository and tracked with version control alongside the codebase to be effective.</blockquote><p><a href="https://jestjs.io/">Jest</a> is a javascript framework that provides us with the capability to run snapshot testing on our codebase. even though we can use <a href="https://jestjs.io/">jest </a>snapshot testing with any framework or even plain HTML/CSS applications we are going to use <a href="https://reactjs.org/docs/getting-started.html">Reactjs</a> for demonstration because <a href="https://reactjs.org/docs/getting-started.html">React </a>comes with support for <a href="https://jestjs.io/">jest</a> out of the box.</p><p><strong>Configuration of Jest snapshot testing on ReactJS</strong></p><blockquote>If you are just interested to see what snapshot testing is and don’t intend to know the configuration detail you can skip to the next section.</blockquote><p>Since react comes with jest out of the box there is not much of configuration we have to do to get up and running. with that said this are the required configuration to setup snapshot testing on ReactJs application.</p><ul><li>Enter the react application directory or create a new one using <a href="https://create-react-app.dev/docs/getting-started/">create-react-app</a></li></ul><pre>create-react-app snap-shot-demo &amp;&amp; cd snap-shot-demo</pre><ul><li>Add <a href="https://www.npmjs.com/package/react-test-renderer">react-test-renderer</a> to your application devDependency inside package.json by running the following code inside a terminal window.</li></ul><pre>npm install --save-dev react-test-renderer<br></pre><p>This package makes it easy to grab a snapshot of the “DOM tree” rendered by a React DOM or React Native component without using a browser or <a href="https://github.com/jsdom/jsdom">jsdom</a>.</p><ul><li>update package.json script section by adding jest as follows</li></ul><pre>...<br>&quot;scripts&quot;: {<br>...<br>&quot;test&quot;: &quot;jest&quot;,<br>...<br>},<br>...</pre><ul><li>because jest doesn’t understand <a href="https://reactjs.org/docs/introducing-jsx.html">JSX</a> we need some way to convert <a href="https://reactjs.org/docs/introducing-jsx.html">JSX</a> to javascript. we will use <a href="https://babeljs.io/docs/en/">babel</a> for this purpose.</li></ul><p>If you are using <a href="https://reactjs.org/docs/getting-started.html">ReactJS</a> version greater than 16 it’s your lucky day because it comes with babel out of the box. but if you are using a version less than 16 you need to add the following devDependencies as well inside your project package.json.</p><pre>npm install --save-dev babel-jest @babel/core @babel/preset-env<br>or<br>yarn add --dev babel-jest @babel/core @babel/preset-env</pre><ul><li>Next, add ababel.config.js file with the following content.</li></ul><pre>module.exports = {<br>presets: [&#39;@babel/preset-env&#39;, &#39;@babel/preset-react&#39;]<br>};</pre><blockquote>for more information refere to the <a href="https://jestjs.io/docs/en/getting-started">official jest configuration</a> and <a href="https://babeljs.io/docs/en/">babeljs documentation</a>.</blockquote><p>The above configuration will work just fine, that is until your component has a direct CSS import like the following</p><pre>import &quot;./EventItem.css&quot;</pre><p>on such cases jest will fail to compile the code because it needs to transform the CSS file to javascript syntax.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YOa0e5yrjBhczfUL5NaS9Q.png" /></figure><p>For this purpose, you have to add another devDependency topackage.json.what worked for me is <a href="https://www.npmjs.com/package/jest-transform-css">jest-transform-css</a> but there is plenty to choose from.</p><p>jest-transform-css is intended to be used in an jsdom environment. When any component imports CSS in the test environment, then the loaded CSS will get added to jsdom using <a href="https://github.com/egoist/style-inject">style-inject</a>.This means the full styles are added to jsdom</p><pre>npm install --save-dev jest-transform-css<br>or <br>yarn add --dev jest-transform-css</pre><p>next, update the transform section of jest.config.js that is found on the root directory of the project. if it doesn’t exists create it by running jest --init</p><pre>transform: {<br>    &#39;^.+\\.js$&#39;: &#39;babel-jest&#39;,<br>    &#39;.+\\.(css|styl|less|sass|scss)$&#39;: &#39;jest-transform-css&#39;<br>}</pre><p>we are telling jest to use <a href="https://www.npmjs.com/package/jest-transform-css">jest-transform-css</a> whenever it encounters CSS, styl, LESS, SASS, SCSS files.</p><p>That’s it you have a project set up and ready for <a href="https://jestjs.io/docs/en/snapshot-testing">snapshot testing</a>. proceed to the next section to see it in action.</p><p>The final package.json file script and devDependency sections should look similar to this</p><pre>...<br>&quot;scripts&quot;: {<br>     ...<br>     &quot;start&quot;: &quot;react-scripts start&quot;,<br>     &quot;build&quot;: &quot;react-scripts build&quot;,<br>     &quot;test&quot;: &quot;jest&quot;,<br>     &quot;eject&quot;: &quot;react-scripts eject&quot;<br>     ...<br>},<br>...<br>&quot;devDependencies&quot;: {<br>    ...<br>    &quot;jest-transform-css&quot;: &quot;^2.0.0&quot;,<br>    &quot;react-test-renderer&quot;: &quot;^16.13.0&quot;<br>    ...<br>}<br>...</pre><p><strong>Getting started</strong></p><p>If you want to run the code in your workspace you can clone this <a href="https://github.com/Mikearaya/snapshot_testing_demo.git">repository</a>.</p><p>make sure you have <a href="https://create-react-app.dev/docs/getting-started/">created-react-app</a> and <a href="https://jestjs.io/">jest</a> installed globally on your work station.</p><pre>npm install -g create-react-app<br>npm install -g jest</pre><p>Snapshot testing works by saving the rendered output of a component at any given moment and comparing that output on the next runs. eg. we could have a react component that renders a list of events.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23b4fdba1bc34e7e34575ea061f089c2/href">https://medium.com/media/23b4fdba1bc34e7e34575ea061f089c2/href</a></iframe><p>as you can see we have a component that accepts event objects withname, startDate &amp; description and renders the output. we can take snapshot of this components first rendered output using<a href="https://jestjs.io/"> jest </a>as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b3d8ce69f11dbfbb0573a0cce9f7118/href">https://medium.com/media/8b3d8ce69f11dbfbb0573a0cce9f7118/href</a></iframe><p>the code above uses <a href="https://www.npmjs.com/package/react-test-renderer">react-test-renderer</a> package to take a snapshot of our component. It takes the following steps when executed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zKhCyNyiI9P_s3kD-wPrEg.png" /><figcaption>i<a href="https://medium.com/@luisvieira_gmr/snapshot-testing-react-components-with-jest-3455d73932a4">mage source</a></figcaption></figure><ul><li>renders the EventItem component using <a href="https://github.com/jsdom/jsdom">jsdom</a></li><li>checks if there exists a snapshot of the component already</li><li>if snapshot doesn’t exist i.e. it is the first time that&#39;s being executed it will create a new snapshot</li><li>if a snapshot already exists it will compare it with the currently rendered component and fails if they don’t match or pass if they match</li></ul><p>The first time we run npm run test <a href="https://jestjs.io/">jest</a> will save the snapshot of the rendered component inside the same directory as the test under a directory named __snapshots__ and file name that has a format of [test-file-name].snap eg. event-item.test.js.snap</p><pre>// Jest Snapshot v1, <a href="https://goo.gl/fbAQLP">https://goo.gl/fbAQLP</a></pre><pre>exports[`EventList Component should render correctly 1`] = `<br>&lt;div<br>  className=&quot;container&quot;<br>&gt;<br>&lt;p&gt;<br>&lt;/p&gt;<br>&lt;span<br>className=&quot;start-date&quot;<br>&gt;<br>&lt;/span&gt;<br>&lt;p&gt;<br>&lt;/p&gt;<br>&lt;/div&gt;<br>`;</pre><p>if for any reason the snapshot file and the rendered output don’t match the next time we run the test it will fail. for example, if I removed the className attribute from the span component and run the test, the test will fail with the following output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9M6h8SXKnzFQQQVqhToF4A.png" /></figure><p>As you can see from the output there is a difference between the previous snapshot and thereceived or current rendered out.</p><p>But what if the change was intentional and you wanted to update the snapshot? well, there is a command we can use for that. you can run the following code and<a href="https://jestjs.io/"> jest</a> will update the snapshot record with the newly rendered output</p><pre>npm run test -- -u<br>or<br>jest --updateSnapshot</pre><p>the above command tells<a href="https://jestjs.io/"> jest </a>to update the snapshot file with the current rendered output and use that for future comparison</p><p><strong>Conclusion</strong></p><p>Snapshot testing is a good addition to our testing arsenal. it will minimize most of the boilerplate code we would have to write to test the application is rendered properly. but by no means, it is a replacement or substitutes to the existing tests such as unit test, integration test, etc... they all serve a different purpose.</p><p>To get the benefits of snapshot testing we should track each snapshot with version control so that the whole team is aware of the changes made and can be used for code review purposes.</p><p>Finally, I don’t recommend taking a snapshot of the whole application instead we should take a snapshot of the sections we want to make sure are rendered correctly. we can use the file size increase for this argument but that will take us no far because the snapshot file size of the jest framework is 30kb but instead the smaller the size the easier it will be later for code review. This comes down to personal preference.</p><p><strong>Reference</strong></p><ul><li><a href="https://jestjs.io/docs/en/getting-started">Jest official documentation</a></li><li><a href="https://reactjs.org/docs/getting-started.html">ReactJs official documentation</a></li><li><a href="https://babeljs.io/docs/en/">babeljs official documentation</a></li><li><a href="https://www.npmjs.com/package/jest-transform-css">jest-transform-css official documentation</a></li><li><a href="https://create-react-app.dev/docs/getting-started/">create-react-app official documentation</a></li><li><a href="https://en.wikipedia.org/wiki/Software_testing">Wikipedia</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e78454aeeba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mikael-araya-blog/snapshot-testing-6e78454aeeba">Snapshot Testing</a> was originally published in <a href="https://medium.com/mikael-araya-blog">Mikael Araya blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript Objects]]></title>
            <link>https://medium.com/mikael-araya-blog/javascript-objects-f8e8f07c1235?source=rss----32ee1f0de2f2---4</link>
            <guid isPermaLink="false">https://medium.com/p/f8e8f07c1235</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[objects]]></category>
            <category><![CDATA[javascript-development]]></category>
            <dc:creator><![CDATA[Mikael Araya]]></dc:creator>
            <pubDate>Wed, 11 Mar 2020 15:59:43 GMT</pubDate>
            <atom:updated>2020-03-26T05:28:33.440Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2A1YJD3KA5yLu_6FSK5zCA.png" /><figcaption><a href="https://catswhocode.com/jquery-document-ready/">image source</a></figcaption></figure><h3>Deep dive In Javascript Objects</h3><p>Objects are an integral part of applications and are used everywhere But despite there ubiquity I think some of there capabilities that could make them even valuable are overlooked especially when it comes to javascript.</p><p>Javascript is an object-based scripting language and understanding the nature of the object especially becomes even more valuable to have control over the core language.</p><p>with the introduction of JavaScript classes, introduced in ECMAScript 2015, the definition of objects has become abstracted. none the less support of class declaration is just syntactic sugar and javascript is still prototype-based and doesn&#39;t add any feature in the existing model. So understanding what the class abstraction performs under the hood is still valuable.</p><blockquote>Refer to the following link if you want a deeper understanding of the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes">ECMAScript 2015 javascript class definition</a>.</blockquote><p>In this article, I’ll try to show most of the properties that relate to javascript object configuration and by the end of this article, I hope you will be more enlightened than you previously were in regards to javascript objects.</p><h4>Introduction</h4><p>Due to the dynamic nature of javascript creating an object is as simple as the code below.</p><pre>var myObject = {};</pre><p>the code above creates an object with a name myObject that extends the base <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a> class prototype with no properties. object prototypical is beyond the scope of this article but you can refer to this <a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes">link</a> if you want to understand more.</p><p>Now if you want to create an object with properties you can modify the above code like below</p><pre>var myObject = {<br>       firstProperty: &#39;&#39;,<br>       secondProperty: 100,<br>       thirdProperty: []<br>}</pre><p>Or add the properties after creating the object</p><pre>var myObject = {};<br>myObject.firstProperty = &#39;&#39;;<br>myObject.secondPropery = 100;<br>myObject.thirdProperty = [];</pre><p>While the above statements are both valid ways of creating an object and initializing its properties, they hide all the configuration that happens in the background.</p><blockquote>In the following section, we will explore all the configuration that is happening in the background at the moment of object creation and try to understand how we can use this configuration option to create objects that fit our requirements.</blockquote><h4>Javascript Objects 101</h4><p>The generic definition of objects in computer science is value in memory that mostly have identifiers that reference them. In javascript objects can be seen as a collection of properties.</p><blockquote>In javascript objects can be seen as a collection of properties.</blockquote><h4>Javascript Object Properties</h4><p>Javascript objects have two properties.</p><ul><li><strong>Data properties</strong> — are properties that hold the actual value of the object and define the behavior of the property.</li><li><strong>Accessor properties</strong> — are properties that are used to modify and retrieve the value from the data properties of the object.</li></ul><p>Each property has attributes that can be used to configure its behavior. while each property have attributes that are unique to each of them there are attributes that are shared between them</p><h4><strong>— Shared Attributes</strong></h4><ul><li><strong>Enumerable(</strong><strong>boolean: false)</strong> — a boolean value that specifies if the property is accessible through iterators like <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in">for…in loops</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax">spread operators</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys">Object.keys()</a>. if left undefined it will take on the default value of false.</li><li><strong>Configurable(</strong><strong>boolean: false) </strong>— a boolean value that specifies if the property can be deleted with the<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete">delete</a> operator. it will take on a default value of false if left unspecified. When attempting to delete the property while on <a href="https://developer.mozilla.org/en-US/docs/Glossary/Sloppy_mode">sloppy mode</a> the operation will be ignored while on strict mode it will throw an error.</li></ul><blockquote><a href="https://developer.mozilla.org/en-US/docs/Glossary/Sloppy_mode">slopy mode</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a> are beyond the scope of this article. if you want a detail discussion make sure you check out each by following there corresponding link.</blockquote><h4><strong>— Data Property Attributes</strong></h4><ul><li><strong>Value(</strong><strong>[string|object|number|Array|null]: </strong><strong>undefined) — </strong>holds the actual value of the property. it can be any valid <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures">javascript data type</a>. when we set the value using this property it’s the same as assigning it directly as we saw it earlier. if left undefined it will take on a default value of undefined.</li><li><strong>Writable (</strong><strong>boolean: false)</strong> — used to specify whether the property can be assigned another value after the moment of creation. if left undefined it will take on the default value of falsewhich means the property becomes read-only.</li></ul><blockquote>If we attempt to reassign new value for a property with the writable value set to false in <a href="https://developer.mozilla.org/en-US/docs/Glossary/Sloppy_mode">sloppy mode</a> the assignment will be ignored while on <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a> it will through error.</blockquote><h4><strong>— Accessor property attributes</strong></h4><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/get"><strong>get (</strong></a><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/get"><strong>Function: undefined)</strong></a> — called whenever we attempt to retrieve the property value associated with this attribute as a function that takes no arguments.</li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/set"><strong>set(</strong></a><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/set"><strong>Function: undefined)</strong></a><strong> </strong>— used to modify the value of a property. it’s a function that is called with one argument that contains the assigned value and is executed whenever a specified property is attempted to be changed.</li></ul><p>As we can see there are a lot of properties we can utilize to configure the property of objects in our application.</p><h4><strong>Mutual Exclusivity between Configurations</strong></h4><p>While we can configure objects however we want there are few configurations that will not work when other configurations are also set.</p><p><strong>Value &amp; writable Vs. set &amp; get assertion</strong></p><ul><li>you can set data writable &amp; valueproperties and also define set and get accessor since they create conflicts.</li></ul><p>on these occasions, it will throw an error similar to oojs.html:34 Uncaught TypeError: Invalid property descriptor. Cannot both specify accessors and a value or writable attribute, #&lt;Object&gt;</p><p>But how do we actually set these values did you say? well, that we’re one of the predefined functions for the global <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects">Object</a> Object.definePropertiy &amp; Object.defineProperties come in to play.</p><h3>Introduction to Object.defineProperty()</h3><p>The global Object provides lots of prefined functions that let us manipulate Objects in various ways and is the superclass to all objects created in javascript.</p><p>Object.definePropery and its sibling Object.defineProperties let us configure the object&#39;s properties as we want. in the following section, we will see how we can use these functions to configure object properties.</p><p>— Object.definePropertytake 3 arguments.</p><p>Object.defineProperty(obj: Object, key: strinng, config: Object)</p><ul><li><strong>Object</strong> — the first argument takes the object to which we want to configure.</li><li><strong>key</strong> — string value that specifies the property we want to modify the attributes of. if the specified key doesn’t exist object.defineProperties will create the key.</li><li><strong>config</strong> — the last argument is used to define the attribute values of the property. we can pass an empty object for this value in which case the default attribute values.</li></ul><pre>Object.defineProperty(Object, &#39;key: String&#39;, {<br>                           configurable: Boolean,<br>                           writable: Boolean,<br>                           enumerable: Boolean,<br>                           value: String|Number|Array|Object,<br>                           get: Function,<br>                           set: Function<br>                      });</pre><p>— its sibling <strong>Object.defineProperties() </strong>takes 2 arguments</p><p>Object.defineProperty(obj: Object, config: Object)</p><ul><li><strong>Object</strong> — the object that you want to configure</li><li><strong>config — </strong>the configuration object.</li></ul><pre>Object.defineProperties(Object, {<br>                 &#39;propertyName&#39;: string    {<br>                           configurable: Boolean,<br>                           writable: Boolean,<br>                           enumerable: Boolean,<br>                           value: String|Number|Array|Object,<br>                           get: Function,<br>                           set: Function<br>                      },<br>                 &#39;propertyName&#39;: string     {<br>                           configurable: Boolean,<br>                           writable: Boolean,<br>                           enumerable: Boolean,<br>                           value: String|Number|Array|Object,<br>                           get: Function,<br>                           set: Function<br>                      },{}...});</pre><h4>Configuring Object properties using Object.create()</h4><p>event though object.defineProperty and Object.defineProperties are dedicated function for setting object properties there is one other way we can we use to set objects properties, that is using the second argument to the function Object.create() that accept property configuration object.</p><pre>var myObject = Object.create({}, {<br>                 &#39;propertyName&#39;: string    {<br>                           configurable: Boolean,<br>                           writable: Boolean,<br>                           enumerable: Boolean,<br>                           value: String|Number|Array|Object,<br>                           get: Function,<br>                           set: Function<br>                      },<br>                 &#39;propertyName&#39;: string     {<br>                           configurable: Boolean,<br>                           writable: Boolean,<br>                           enumerable: Boolean,<br>                           value: String|Number|Array|Object,<br>                           get: Function,<br>                           set: Function<br>                      }...} )</pre><h3><strong>Examples</strong></h3><p>In the following section, I’ll try to show different configuration options we can follow in applications.</p><h4>1 Object with a default value</h4><pre>var myObject = {};<br>Object.defineProperty(myObject, &#39;firstProperty&#39;, {<br>                        configurable: false, <br>                        writable: true,<br>                        value: 200,         //default value<br>                        enumerable: false,<br>                        set(val) {<br>                               this.first = val;<br>                        },<br>                        get() {<br>                               return this.first;<br>                        }<br>                     });<br></pre><pre>&gt; console.log(myObject);<br>&gt; 200 </pre><h4>2 Read-only property — Soppy-mode</h4><pre>var myObject = {};<br>Object.defineProperty(myObject, &#39;firstProperty&#39;, {<br>                                       configurable: false,<br>                                       writable: false,<br>                                       value: 200,<br>                                       enumerable: false<br>                      });</pre><pre> myObject.firstProperty = 100; // will not affect the value</pre><pre>console.log(myObject.firstProperty);<br>&gt; 200  // same as defined inside object.defineProperty()</pre><h4>3 Read-only property — strict-mode</h4><pre>&#39;use strict&#39;; // strict mode</pre><pre>var myObject = {};<br>Object.defineProperty(myObject, &#39;firstProperty&#39;, {<br>                                       configurable: false,<br>                                       writable: false,<br>                                       value: 200,<br>                                       enumerable: false<br>                      });</pre><pre>myObject.firstProperty = 100; // will throw error</pre><pre>console.log(myObject.firstProperty);</pre><pre>&gt; Uncaught TypeError: Cannot assign to read only property &#39;firstProperty&#39; of object &#39;#&lt;Object&gt;&#39;</pre><h4>4. Setting Multiple values using Object.defineProperties</h4><pre>var myObject = {};<br>Object.defineProperties(myObject, {<br>                    firstProperty: {<br>                                     configurable: false,<br>                                     writable: true,<br>                                     value: 200,<br>                                     enumerable: false<br>                                    },<br>                   secondProperty: {<br>                                     configurable: false,<br>                                     writable: true,<br>                                     value: 100,<br>                                     enumerable: false<br>                                   }<br>                  });<br></pre><pre>&gt; console.log(myObject.firstProperty);<br>&gt; 200<br>&gt; console.log(myObject.secondProperty);<br>&gt; 100</pre><h4>5 Hide property from Iterators</h4><pre>var myObject = {};<br>Object.defineProperties(myObject, {<br>                       firstProperty: {<br>                           configurable: false,<br>                           writable: true,<br>                           value: 200,<br>                           enumerable: true<br>                       },<br>                       secondProperty: {<br>                            configurable: false,<br>                            writable: true,<br>                            value: 100,<br>                       // hidden from itterators  <br>                            enumerable: false <br>                           }<br>                         });</pre><pre>     for (const key in myObject) {<br>              console.log(key);<br>      }</pre><pre>&gt; firstProperty</pre><h4>6 Restrict Delete — slopy mode</h4><pre>var myObject = {};</pre><pre>Object.defineProperty(myObject, &#39;firstProperty&#39;, <br>                                    {<br>                                 // disable delete<br>                                      configurable: false,<br>                                      writable: true,<br>                                      value: 200,<br>                                      enumerable: true<br>                      });</pre><pre>// does not have any effect<br>delete myObject.firstProperty; </pre><pre>console.log(myObject.firstProperty);<br>&gt; 200 // value still available</pre><h4>7 Restrict Delete — slopy mode</h4><pre>&#39;use strict&#39;;</pre><pre>var myObject = {};</pre><pre>Object.defineProperty(myObject, &#39;firstProperty&#39;, <br>                                    {<br>                                 // disable delete<br>                                      configurable: false,<br>                                      writable: true,<br>                                      value: 200,<br>                                      enumerable: true<br>                      });</pre><pre>// will throw error since firstProperty is not configurable<br>delete myObject.firstProperty;</pre><pre>console.log(myObject.firstProperty);</pre><pre>&gt; Uncaught TypeError: Cannot delete property &#39;firstProperty&#39; of #&lt;Object&gt;</pre><h4>8 Define accessor for property</h4><pre>var myObject = {};<br>Object.defineProperty(myObject, &#39;firstProperty&#39;, {<br>                                      <br>                               configurable: false,<br>                               enumerable: true,<br>                               get() {  return this.first;},<br>                               set(val) {<br>                            // change value to uppercase</pre><pre>                           return (this.first = val.toUpperCase());<br>                                });</pre><pre>myObject.firstProperty = &#39;Mikael Araya&#39;;<br>console.log(myObject.firstProperty);</pre><pre>&gt; MIKAEL ARAYA</pre><h4>9 Define object property using Object.create</h4><pre>var myObject = Object.create({}, {<br>                    firstProperty: {<br>                                     configurable: false,<br>                                     writable: true,<br>                                     value: 200,<br>                                     enumerable: false<br>                                    },<br>                   secondProperty: {<br>                                     configurable: false,<br>                                     writable: true,<br>                                     value: 100,<br>                                     enumerable: false<br>                                   }<br>                  });<br>console.log(myObject.firstProperty);<br>&gt; 200<br>console.log(myObject.secondProperty);<br>&gt; 100</pre><h4>Conclusion</h4><p>While there are many libraries and frameworks out there abstracting the underline javascript engine understanding how some aspects of the language are implemented is essential to have great control over the tool.</p><p>Defining object property attributes explicitly instead of passing to javascript default behavior will enable us to have control over how objects in application behave and increase predictability and security.</p><p><strong>Reference</strong></p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties">Object.defineProperties MDN web documentation</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties">Object.definePropery MDN web documentation</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object">Object MDN web documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8e8f07c1235" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mikael-araya-blog/javascript-objects-f8e8f07c1235">Javascript Objects</a> was originally published in <a href="https://medium.com/mikael-araya-blog">Mikael Araya blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hosting static website on Github Pages for Free]]></title>
            <link>https://medium.com/mikael-araya-blog/hosting-static-website-on-github-pages-for-free-570e90d6dabd?source=rss----32ee1f0de2f2---4</link>
            <guid isPermaLink="false">https://medium.com/p/570e90d6dabd</guid>
            <category><![CDATA[github-pages]]></category>
            <category><![CDATA[web-hosting]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[static-websites]]></category>
            <dc:creator><![CDATA[Mikael Araya]]></dc:creator>
            <pubDate>Wed, 19 Feb 2020 15:36:17 GMT</pubDate>
            <atom:updated>2020-02-19T17:08:53.737Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*yoCuNmAT-IZM_gMGcMpP6Q.jpeg" /><figcaption><a href="https://courseit.com.ar/blog/content/images/2019/10/banner--1-.jpg">image source</a></figcaption></figure><h3>How to Host static website for Free on Github Pages</h3><p>In this era of information where everything can be found instantly, where you can purchase an item from another continent, having an online presence has become a necessity rather than a choice if you want to stay relevant. While there are many service providers that we can use to host our website with a monthly or yearly subscription for a price; in this article, I’ll try to show you how you can set up your own website with no payment at all, yes you read that correctly no payment at all using <a href="https://pages.github.com/">GitHub pages</a>.</p><p>Github is a well-known website by the developer&#39;s community because they use it to manage their code base and is almost considered as a nerds website. But good for everyone because even nerds need an online presence if not, even more, and GitHub enables each Github repository to host a static page one for the entire repository and one for each repository.</p><p>In this article, we will use the option to create one repository website.</p><p><strong>Prerequisites</strong></p><ul><li>You need to have a git version control software since it’s the <a href="https://git-scm.com/">git</a> to the hub if you know what I mean :-). so make sure you have <a href="https://git-scm.com/">git</a> installed on your system.</li><li>If you don’t have a GitHub account already make sure you <a href="https://github.com/join">create one</a></li></ul><p><strong>Getting Started</strong></p><p>If you have are not using git as version control for your site source code make sure to create a new repository and link it with a GitHub repository by following <a href="https://help.github.com/en/github/importing-your-projects-to-github/adding-an-existing-project-to-github-using-the-command-line">this guide</a> before proceeding. make sure to create a repository with the following name</p><pre>[username].github.io</pre><blockquote>Note that this is a very important configuration. the repository where you will deploy your site should match the above pattern. if you have your own domain you can link your domain with a Github pages, that way your source code will be hosted for free and you can use your private domain to access it like so <a href="https://yourdomain.com|org"><strong>https://yourdomain.(com|org</strong></a><strong>|io|net) etc…</strong>.</blockquote><p>Now that you have a git repository initialized and added to the Github repository the next thing we need to do is deploy it as a using <a href="https://pages.github.com/">GitHub page</a>.</p><p>There are three ways we can deploy our repository on GitHub pages.</p><ul><li>Deploy from the <strong>master</strong> branch of the repository</li><li>Deploy from<strong> </strong>the <strong>gh-pages</strong> branch</li><li>Deploy from the docs folder inside <strong>master</strong> branch</li></ul><p>In this article, we will deploy our code from the master branch but you should explore what each deployment method does and how they differ <a href="https://help.github.com/en/github/working-with-github-pages/configuring-a-publishing-source-for-your-github-pages-site">from here</a>.</p><p>That&#39;s it we are done with all the configuration required on our localhost. push any changes you have made.</p><pre>git push master origin</pre><p>after pushing to the repository go to the GitHub and <strong><em>setting &gt; options</em></strong> tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AkW4-KoQuarDU_MK-v4d7g.png" /></figure><p>Next, scroll down until you find the pages section. Once you found the pages section you will find a dropdown button with source label where you can select from which section we mentioned previously you want to deploy your page from and you should see the <strong><em>master</em></strong> branch we created previously from the options. select the <strong><em>master</em></strong> branch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kA12RDWXrP54hU4zyJdOyg.png" /></figure><p>Congratulation you can visit your website deployed on the internet and you can access it from anywhere using</p><pre> <a href="https://www.github.com/[username]">https://</a><a href="https://www.github.com/[username]">[username]</a><a href="https://www.github.com/[username]">.github.</a>io</pre><p>you can use static page generator <strong>J</strong><a href="https://jekyllrb.com/docs/"><strong>eklin</strong></a> library themes that are supported by default with GitHub pages if your sites don&#39;t have its own theme implementation. you can learn more about that <a href="https://help.github.com/en/github/working-with-github-pages/adding-a-theme-to-your-github-pages-site-with-the-theme-chooser">from here</a>.</p><p>Now that I have shown you how to deploy your static website for free, I think I should give my opinion about the pros and cons of using GitHub pages.</p><p><strong>Pros</strong></p><ul><li>It’s Free — This is probably one of the reasons you are reading this article in the first place.</li><li>Secure &amp; Reliable — well it’s hosted on the GitHub server so that says a lot about that</li><li>You have full control over your site’s look &amp; feel</li></ul><p><strong>Cons</strong></p><ul><li>It’s Static</li><li>You’ll need to take special measures for SEO</li><li>No Support</li></ul><p><strong>Reference</strong></p><ul><li><a href="https://pages.github.com/">Github pages official documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=570e90d6dabd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mikael-araya-blog/hosting-static-website-on-github-pages-for-free-570e90d6dabd">Hosting static website on Github Pages for Free</a> was originally published in <a href="https://medium.com/mikael-araya-blog">Mikael Araya blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Run time Optimization of Angular Application using Caching]]></title>
            <link>https://medium.com/mikael-araya-blog/run-time-optimization-of-angular-application-using-caching-9f1fab73c541?source=rss----32ee1f0de2f2---4</link>
            <guid isPermaLink="false">https://medium.com/p/9f1fab73c541</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Mikael Araya]]></dc:creator>
            <pubDate>Sat, 15 Feb 2020 15:46:50 GMT</pubDate>
            <atom:updated>2020-02-15T19:45:20.709Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*qNTYOLc_aRPZqiPmjgeTug.jpeg" /><figcaption><a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fwww.cmarix.com%2Fhow-to-utilise-the-caching-mechanism-in-angular-for-app-development%2F&amp;psig=AOvVaw0AEyz7e9oqznf-gY7V6pEs&amp;ust=1581866552177000&amp;source=images&amp;cd=vfe&amp;ved=0CA0QjhxqFwoTCOi27KTu0-cCFQAAAAAdAAAAABAD">image source</a></figcaption></figure><p>As our application gets traction and users start using them for the task they were built for we start worrying about optimization so that users will have a great experience while using our application.</p><p>There are many optimization technics and optimizable areas we can follow to make the performance of our application good for our end users. such as</p><ul><li>Design level</li><li>Algorithms &amp; data structure</li><li>Build level</li><li>Compile Level</li><li>Assembly level</li><li>Run time</li><li>Platform dependent &amp; Independent optimization &amp; more</li></ul><p>Although there is no one right method we can follow to optimize our system &amp; that we should try to optimize our application at every level, in this article we are going to see optimization applied at run time through caching.</p><p>There is a major problem we face once our applications start being used by the end-user. As the amount of data stored in the database grows exponentially so does the time needed to read from the database. The obvious way to solve this problem would be to increase our processing power in relation to the data; which will do the job but is also costly. Another way we can approach this problem would be by implementing caching.</p><blockquote>when caching, our main goal is to minimize the number of requests we make to fetch data. we can achieve this by storing each response from the datastore in memory so that the next time we want to read data we have previously fetched we simply read from memory without executing any code on the database.</blockquote><p>In this article, I’ll try to show one way of implementing caching in our angular application.</p><p>Since you are reading about optimizing angular application it’s fair for me to assume you have at least the basics of angular and what angular application is composed of; so we can jump straight to the implementation without taking a detour.</p><p>with that said I am not going to introduce a detailed discussion about angular interceptors and services if you need a refresher on these topics to make sure to go through the following links before proceeding.</p><ul><li><a href="https://angular.io/tutorial/toh-pt4">Angular Service</a></li><li><a href="https://angular.io/api/common/http/HttpInterceptor">Angular Interceptors</a></li></ul><p><strong>Prerequisites</strong></p><ul><li><a href="https://angular.io/docs"><strong>Angular V6.x&lt;</strong></a><strong>=</strong></li><li><strong>node.js V8.x &lt;=</strong></li></ul><p><strong>Getting Started</strong></p><blockquote>What we are trying to achieve is a mechanism by which we can, whenever we try to make a request to the server for some data, to check if we have made the same request before; if so cancel the request &amp; retrieve the data from memory else make the request and save the response in memory so we will not make the same request again.</blockquote><p>We can achieve this using an <a href="https://angular.io/api/common/http/HttpInterceptor">angular interceptor </a>in combination with <a href="https://angular.io/tutorial/toh-pt4">angular service</a>. Interceptors allow us to check every request that goes in &amp; out of our system. That’s exactly what we will need to achieve in our caching mechanism. implementation of interceptors is no more different than the implementation of angular service, their difference comes on how we inject them in the angular component tree; which we will see later.</p><p>After you have set up your environment and are ready lets first create the general-purpose service we will use to manage the cache inside the interceptor we will call it <strong>SystemCache</strong>.</p><pre>ng generate service SystemCache</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f265b4caf0c56e15ed9c2aaf3fdfc5fa/href">https://medium.com/media/f265b4caf0c56e15ed9c2aaf3fdfc5fa/href</a></iframe><p>We have defined two properties:</p><ul><li><strong>cacheMap — </strong>used to<strong> </strong>hold each request cached.</li><li><strong><em>MAX_CACHE_AGE</em></strong> — a constant that will specify the maximum cache age in a millisecond to determine when we should delete a cache.</li></ul><p>Also, you can see in <strong><em>system-cache.service.ts</em></strong><em> </em>we have defined three methods:</p><ul><li><strong>get</strong> — which accepts one argument <a href="https://angular.io/api/common/http/HttpRequest">HttpRequest</a></li><li><strong>deleteExpiredCache — </strong>which will delete all the expired caches in memory so that we get updated information.</li><li><strong>put — </strong>which will be used to store new data that will be cached</li></ul><p>Let’s examine what we are doing inside each function.</p><p><strong>get — </strong>the first thing we do is clear any expired cache inside the memory by calling <strong>deleteExpiredCache</strong> function. Next, we checked if we have the request already in memory or not if we don’t have it already we return a <strong>null</strong> indicating to make the request else we return the data.</p><pre>const entry = this.cacheMap.get(req.urlWithParams);<br>if (!entry) { return null; }</pre><p>If the cache exists but has expired we return <strong>null </strong>else we return the entry from the cache</p><pre>const isExpired = Date.now() - entry.entryTime &gt; MAX_CACHE_AGE;<br>return isExpired ? null : entry.response;</pre><ul><li><strong>put — </strong>This function will be used to store new value on our in-memory storage. it takes two arguments <a href="https://angular.io/api/common/http/HttpRequest">HttpRequest</a> and the corresponding <a href="https://angular.io/api/common/http/HttpResponse">HttpResponse</a> holding the response data. using the parameters passed to it we only need the request URL to be used as a key associated with the data retrieved from the server then we add a timestamp to record when this data was received from the server.</li><li><strong>deleteExpiredCache — </strong>used to delete cache entries that exceed the <em>MAX_CACHE_AGE</em> value we have defined to make sure the data is consistent.</li></ul><p>Now that we have our general-purpose setup &amp; ready the next step is to create the interceptor that will check each request made from our app and utilize this service to manage the caching of the application.</p><p>Go to the root directory on the terminal and create the service that will be used as an interceptor, let’s call it <strong>SystemCacheInterceptor.</strong></p><pre>ng generate service SystemCacheInterceptor</pre><p>Like I mentioned previously interceptors are ordinary services that implement the <a href="https://angular.io/api/common/http/HttpInterceptor">HttpInterceptor</a> interface. with that said let’s update the new service by copying the code below &amp; we will discuss what each line does next.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0321ef65db998c0bee9ed85d884b1020/href">https://medium.com/media/0321ef65db998c0bee9ed85d884b1020/href</a></iframe><p>The system cache interceptor service implements the <a href="https://angular.io/api/common/http/HttpInterceptor">HttpInterceptor</a> interface which requires the <em>intercept</em> function to be implemented. We have also injected the general-purpose service we created <strong><em>SystemCacheService</em></strong> inside the constructor.</p><p>inside the intercept function, the first thing we did was check the current request method and whether if it’s a <strong>GET</strong> request or not.</p><blockquote>Note that this implementation only caches GET request for simplicity purpose but you can extend this to handle multiple request method types for your needs. eg. you can implement a DELETE request handle that will delete the record from cache if the user deletes it from datastore.</blockquote><p>If the request is not GET we simply pass the current request to the next interceptors that might be in our system by calling the handle method from the HttpHandler since we are only caching GET requests.</p><p>When a request is an HTTP GET request we first check if we have already made the request previously by using the get method from <strong>SystemCacheService </strong>which returns the cached value from memory or <strong>null</strong>.</p><pre>const cachedResponse = this.systemCache.get(req);</pre><p>Then we check if the value of the returned value and return the cached value if it’s found; canceling the request else make the request to get fresh data.</p><pre>if (cachedResponse !== null) { return of(cachedResponse); }</pre><p>Since we haven’t made the request previously we need to store the response value inside our cache so that we will not make the same request in later times. that’s what we just did in this line of code.</p><pre>return next.handle(req).pipe(<br>     tap(event =&gt; {<br>        if (event instanceof HttpResponse) {<br>           this.systemCache.put(req, event);<br>        }<br>     })<br>  );</pre><p>That is, we have created our interceptor successfully the only thing left is registering it in the angular HTTP request pipeline for it to start working.</p><p>we will do that by providing it just like any other service inside our module. go ahead to your top-level module and modify it by adding the code below</p><pre>import { HTTP_INTERCEPTORS } from &#39;@angular/common/http&#39;;<br>...<br>@NgModule({<br>...<br>     providers: [ { <br>                provide: HTTP_INTERCEPTORS,<br>               useClass: SystemCacheInterceptorService,<br>               multi: true<br>            },<br>       ]<br>...<br>})</pre><blockquote>Note that in order for the interceptor to catch all the requests that come in &amp; out of the application you need to provide it at the top level of the dependency tree. read more about angular dependency tree <a href="https://angular.io/guide/dependency-injection-providers">here</a></blockquote><p>We are telling angular to use the HTTP_INTERCEPTORS class with the implementation found inside SystemCacheInterceptorService. the <strong><em>multi: true </em></strong>option is critical since we might implement different types of interceptors in our application by setting this we are telling angular to look for another interceptor after completing our interceptor logic otherwise it would stop looking for interceptors.</p><p>We are set and done you can serve your application and see the caching mechanism in action.</p><p>You can further modify the logic we have to see to fit your needs but the underlying logic will not be any different.</p><p><strong>Reference</strong></p><ul><li><a href="https://en.wikipedia.org/wiki/Program_optimization">Program Optimization — Wikipedia</a></li><li><a href="https://angular.io/docs">Official Angular Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f1fab73c541" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mikael-araya-blog/run-time-optimization-of-angular-application-using-caching-9f1fab73c541">Run time Optimization of Angular Application using Caching</a> was originally published in <a href="https://medium.com/mikael-araya-blog">Mikael Araya blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Controlling Visibility of component Based on User Claims using Angular Structural Directives]]></title>
            <link>https://medium.com/mikael-araya-blog/controlling-visibility-of-component-based-on-user-claims-using-angular-directives-deb350b7493?source=rss----32ee1f0de2f2---4</link>
            <guid isPermaLink="false">https://medium.com/p/deb350b7493</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Mikael Araya]]></dc:creator>
            <pubDate>Wed, 05 Feb 2020 18:43:55 GMT</pubDate>
            <atom:updated>2020-02-05T19:27:46.840Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*ng5JLLCCVcvuJvrAMR-cNw.jpeg" /></figure><h3>Controlling Visibility of component Based on User Claims using Angular Structural Directive</h3><p>In my <a href="https://medium.com/mikael-araya-blog/angular-restricting-user-access-using-claim-based-authorization-with-router-guard-844184f3a029?source=friends_link&amp;sk=7518fed27e46d98d52023ba1097e24c2">previous article</a>, I tried to show one way of implementing claims-based authorization in angular using router guards. if you haven’t read that article I suggest you go through that and return here, as most of the components and services we are going to use are described in that article.</p><p>In the previous article, the main focus was on protecting users from navigating to an entire page in which they are not authorized to. That is one step of implementing authorization we also want to hide elements to a specific section of our application in which they don’t have the authorization to use or view.</p><p>That is what we are going to achieve in this article, we will hide or show certain elements or sections inside our page using custom angular directive even if the user is authorized to view the page. eg. of this would be a user is authorized to view a list of all employee records but he/she is not authorized to edit the employee record. in this case, we want to hide the edit button entirely from the view even if we have a <a href="https://angular.io/guide/router">route guard</a> preventing him/her from navigating to the edit view; you can see it as extra level security.</p><p>You can see the end result of what we are going to accomplish on this stackblitz project I’ve created.</p><p><a href="https://stackblitz.com/edit/angular-zl6rnx?embed=1&amp;file=src/app/app.component.html&amp;hideExplorer=1">angular-zl6rnx - StackBlitz</a></p><p>Or you can see the deployed version of the application <a href="https://mikearaya.github.io/angular-authentication-directive/">here</a>.</p><blockquote>Note: when switching between roles you need to refresh the browser in order to see the effect take place.</blockquote><p><strong>Prerequisites</strong></p><p>so before starting working on this project make sure you have all the pre-requisites on your development environment. In order to accomplish what we want we are not going to rely on external dependencies we only going to use tools provided by angular:</p><ul><li><a href="https://nodejs.org/en/">Node.js</a> ≥ 10.x</li><li>Angular CLI ≥ 7.x</li></ul><p>Now that you have all the pre-requisites on your development environment clone the repositor we have create in the previous article so that we can modify and add the visibility feature to it:</p><ul><li><a href="https://github.com/Mikearaya/angular-authentication-complete.git">Github repository</a></li></ul><p>next enter the repository you have just clone and install of it’s dependencies before starting the application:</p><pre>cd angular-authenntication-directive<br>npm i<br>ng serve -o</pre><p>after executing the following commands and compilation completes you should see the browser window open up with a view similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*46Ai0AJzXo3irs74cRHobg.png" /><figcaption><a href="https://mikearaya.github.io/angular-authentication-complete">claim based authorization implementation with only route guards</a></figcaption></figure><p><strong>Project Recap</strong></p><p>We have three types of users and three sections on the application. home page section, user section &amp; admin section respectively.</p><p>Anyone with canViewAdminSection claims has access right to the entire application while users with canViewUserSection have access right to users section but not admin area and normal users can only access the public area of the application.</p><p><strong>Getting started</strong></p><p>We can now start implementing our custom directive to implement the visibility feature we want to add. open the application with your favorite IDE and try to understand it’s a basic structure and how each component interacts with each other.</p><p><a href="https://angular.io/guide/attribute-directives">Directives</a> are used to manipulate the DOM based on a certain condition. they are used to extend the power of HTML by giving it new syntax. Each <strong>directive</strong> has a name. Angular provides predefined directives out the box such as ng-if, ng-for, ng-hide, etc…or you can create custom one which can be called anything.</p><p>There are three kinds of directives in Angular:</p><ol><li><strong>Components </strong>— directives with a template.</li><li><strong>Structural directives </strong>— change the DOM layout by adding and removing DOM elements.</li><li><strong>Attribute directives </strong>— change the appearance or behavior of an element, component, or another directive.</li></ol><p>For a detailed description about directive refer to the<a href="https://angular.io/guide/attribute-directives"> a</a>n<a href="https://angular.io/guide/attribute-directives">gular official docume</a>n<a href="https://angular.io/guide/attribute-directives">tatio</a>n</p><blockquote>For our purpose, we are going to use a Structural directive to show or hide elements from view based on the user&#39;s claim.</blockquote><p>now let’s create the custom directive we will call it HasClaim directive since it’s purpose is to check if a user has a claim or not:</p><pre>ng generate directive HasClaim</pre><p>we can see CLI generated code looks something like this.</p><pre>import { Directive } from &#39;@angular/core&#39;;</pre><pre>@Directive({ <br>      selector: &#39;[appHasClaim]&#39;<br>  })<br>export class HasClaimDirective {<br>   constructor() { }<br>}</pre><p>Notice the selector name has a prefix <strong>app </strong>that angular includes by default so that collision with HTML and other library attributes doesn’t occur, you can change it to any value you want.</p><p>what this directive is going to do is accept a claim value as input and whether the current user has that claim value set to true it will show the elements it is attached to else it will remove it from the view; simple as that.</p><p>In order to achieve this requirement, we need to make use of several services injected into our directive.</p><ul><li><a href="https://angular.io/api/core/TemplateRef"><strong>TemplateRef&lt;any&gt; from @angular/core </strong></a><strong>— </strong>is used to instantiate element into our view with the help of another service <a href="https://angular.io/api/core/ViewContainerRef"><strong>ViewContainerRef</strong></a><strong> .</strong></li><li><a href="https://angular.io/api/core/ViewContainerRef"><strong>ViewContainerRef</strong></a><strong> — </strong>is used to inject the element reference by <a href="https://angular.io/api/core/TemplateRef"><strong>TemplateRef&lt;any&gt;</strong></a><strong> </strong>inside our view.</li><li><strong>SecurityService — </strong>this is the service we created on the previous article and will be used to check if the user has a claim or not using it’s <em>hasClaim</em> method.</li></ul><p>let’s go ahead and inject the above service inside the constructor and add the import statement for each package.</p><pre>import { TemplateRef, ViewContainerRef} from &quot;@angular/core&quot;;<br>import { SecurityServiceService } from &quot;./security-service.service&quot;;</pre><pre>---<br>constructor(<br>      private templateRef: TemplateRef&lt;any&gt;,<br>      private viewContainer: ViewContainerRef,<br>      private securityService: SecurityServiceService<br>) {}<br>---</pre><p>next, we need some way to pass the claim values down to our component lucky angular has got us covered; we can use the <a href="https://angular.io/api/core/Input">@Input</a> decorator to pass data down the component tree. go ahead and define it in our custom directive as follows:</p><pre>@Input(&quot;appHasClaim&quot;) set hasClaim(claimType: any){}</pre><p>we have just defined out Input but haven’t defined all of its functionalities yet. we gave our input an alias; inside the directive, it’s known as <em>appHasClaim</em> but from the outside, we use hasClaim to attach it to any HTML element.</p><p>now let&#39;s add the code that is used to decide when to inject or remove an element from view in our directive Input function update the above code with the code given below then we will discuss what we are doing.</p><pre>@Input(&quot;appHasClaim&quot;) set hasClaim(claimType: any) {<br>    this.securityService.hasClaim(claimType).subscribe(e =&gt; {<br>         if (e) {<br>          this.viewContainer.createEmbeddedView(this.templateRef);<br>         } else {<br>          this.viewContainer.clear();<br>         }<br>   });<br>}</pre><p>The first thing we did was subscribe to the hasClaim function of the security service we created previously and pass it the claim value to it. based on the result we get if the user has the claim set to true we inject/add the element inside the view else we remove it from the view.</p><p>That it!!!, we have created our custom directive all that is left now is start using it. make sure you have declared it inside AppModule before you can start using it.</p><pre>@NgModule({<br>...     <br>  declarations: [ <br>...<br><strong>HasClaimDirective </strong><br>...<br>],<br>... <br>})</pre><p>Go to <a href="https://github.com/Mikearaya/angular-authentication-directive/blob/master/src/app/app.component.html">src/app/app.component.html</a> and update it by including the custom directive we have created to hide or show the elements.</p><pre>...<br>    &lt;li class=&quot;nav-item active&quot;&gt;<br>       &lt;a class=&quot;nav-link&quot;  routerLink=&quot;/admin&quot;<br><strong>          *appHasClaim=&quot;&#39;canViewAdminSection&#39;&quot;</strong><br>       &gt;<br>   Admin<br>       &lt;/a&gt;<br>   &lt;/li&gt;<br>   &lt;li class=&quot;nav-item active&quot;&gt;<br>      &lt;a class=&quot;nav-link&quot; routerLink=&quot;/user&quot;<br><strong>         *appHasClaim=&quot;&#39;canViewUserSection&#39;&quot;</strong><br>       &gt;<br>   User<br>     &lt;/a&gt;<br>  &lt;/li&gt;<br>....<br>  &lt;button type=&quot;button&quot; class=&quot;btn btn-primary m-2&quot;<br><strong>     *appHasClaim=&quot;&#39;canViewAdminSection&#39;&quot;</strong><br>      routerLink=&quot;/admin&quot;<br>   &gt;<br>       Go To Admin<br>  &lt;/button&gt;<br>  &lt;button  type=&quot;button&quot;  class=&quot;btn btn-secondary m-2&quot;<br><strong>     *appHasClaim=&quot;&#39;canViewUserSection&#39;&quot;</strong><br>      routerLink=&quot;/user&quot;<br>   &gt;  <br>      Go to User<br>  &lt;/button&gt;</pre><p>I have removed all the unnecessary code and only included the part we need to modify for our directive to take effect. Notice <strong>* </strong>symbol added before the directive name, it’s not a typo error, make sure you add it so that angular can detect it as a directive otherwise you will get <strong>StaticInjector</strong> error.</p><p>We are done, make sure you saved everything and run the following command to start the application.</p><pre>ng serve -o</pre><p>The final structural directive class should look like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21fabccfceab16f9377aef36b32a4a81/href">https://medium.com/media/21fabccfceab16f9377aef36b32a4a81/href</a></iframe><p>you can find the complete code from my <a href="https://github.com/Mikearaya/angular-authentication-directive">Github Repository</a></p><p><strong>Reference</strong></p><ul><li><a href="https://angular.io/docs">Angular Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=deb350b7493" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mikael-araya-blog/controlling-visibility-of-component-based-on-user-claims-using-angular-directives-deb350b7493">Controlling Visibility of component Based on User Claims using Angular Structural Directives</a> was originally published in <a href="https://medium.com/mikael-araya-blog">Mikael Araya blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular: Restricting User Access Using Claim Based Authorization With Router Guard]]></title>
            <link>https://medium.com/mikael-araya-blog/angular-restricting-user-access-using-claim-based-authorization-with-router-guard-844184f3a029?source=rss----32ee1f0de2f2---4</link>
            <guid isPermaLink="false">https://medium.com/p/844184f3a029</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[angular-4]]></category>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[angularjs]]></category>
            <dc:creator><![CDATA[Mikael Araya]]></dc:creator>
            <pubDate>Sun, 02 Feb 2020 13:15:31 GMT</pubDate>
            <atom:updated>2020-02-02T13:20:00.545Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*CiqgP7tVdKhtVJNIC9td0w.png" /></figure><h3>Angular: Restricting user access Using claim based Authorization With Router Guard</h3><p>While often used interchangeably, <a href="https://auth0.com/docs/application-auth/current">authentication</a> and <a href="https://auth0.com/docs/authorization">authorization</a> serve a fundamentally different purpose.</p><blockquote>Authentication is the process of identifying whether the provided credential by a certain user is valid or invalid whicle authorization is the process of checking if that user has access right to a certain feature or area of our application.</blockquote><p>In this article, we are going to explore how we can implement authentication in our angular application. There are different types of authorization we can implement in our application, the most common authentication methods are:</p><ul><li><a href="https://en.wikipedia.org/wiki/Role-based_access_control"><strong>Role-Based authorization</strong></a> — This type of authorization is implemented by creating different roles in a system and assigning each <a href="https://auth0.com/docs/application-auth/current">authenticated</a> user with one or more roles which in turn are linked to privileges on the system by the system administrator or someone who has the privilege to do so.</li><li><a href="https://en.wikipedia.org/wiki/Claims-based_identity"><strong>Claim-based authorization</strong></a> — Claims-based identity abstracts the individual elements of identity and <a href="https://en.wikipedia.org/wiki/Access_control">access control</a> into two parts: a notion of claims, and the concept of an issuer or an authority. A claim is a statement that one subject makes about themselves. It is a list of key-value pares that identify what each user has to say about themselves.</li></ul><p>A real-world example would be when you are driving a vehicle and the traffic police stop you, suspecting you are younger than 18 years. Then, you take out your driving license and claim that you are a perfectly legal age to drive. The police accept your claim and let you drive on.</p><blockquote>In short, Claims are pieces of information about a user that have been packaged, signed into security tokens and sent by an issuer or identity provider to relying upon party applications through a security token service (STS). The data is then transmitted using a standard method, such as the <a href="https://searchsecurity.techtarget.com/definition/SAML">Security Assertion Markup Language</a> (SAML), Javascript Object Notation (JSON) so that the claims will have the same format across different authentication sources and applications.</blockquote><p>In this article, we are going to explore how we can achieve claim based authorization in our angular application to allow or deny access to a system.</p><p>If you are interested in seeing role-based authorization in angular, comment below and we will go through each step together on another article.</p><p><strong>Prerequisites</strong></p><blockquote>Even though knowledge of angular is not required to follow this article all the code required is provided; I am assuming the reader has at least a basic understanding of angular or even has used it to develop applications previously.</blockquote><p>We are going to add authorization in our angular application using the existing tools that come pre-packaged within angular.</p><p>Angular router module allows us to use router guards to allow or prevent navigation to a certain module or component, we are going to leverage this built-in tool to work with our custom claim based service. if you want to learn more about angular router refer to the official <a href="https://angular.io/guide/router">documentation</a>.</p><p>With that said make sure you have the following tools installed and configured on your system.</p><ul><li><a href="https://nodejs.org/en/">Node.js 8.x &lt;=</a></li><li><a href="https://angular.io/">Angular 7.x &lt;=</a></li><li><a href="https://getbootstrap.com/docs/4.4/getting-started/download/">Bootstrap 4</a></li><li><a href="https://jquery.com/download/">Jquery</a></li><li><a href="https://popper.js.org/">Popper.js</a></li></ul><p><strong>Getting Started</strong></p><p>Before we start babbling all these technical terms go ahead and check the stackblitz project I have created for this article to understand what we are trying to accomplish at the end of this article.</p><p><a href="https://stackblitz.com/edit/angular-uhufqc?embed=1&amp;file=src/app/admin-section/admin-section.module.ts&amp;hideNavigation=1">angular-uhufqc - StackBlitz</a></p><p><strong>You can also check out the deployed version of the application found </strong><a href="https://mikearaya.github.io/angular-authentication-complete/"><strong>here</strong></a><strong>.</strong></p><p><strong>Scope.</strong></p><ul><li>Restrict user access to modules and components in our application.</li></ul><p><strong>Limitation</strong></p><ul><li>Controlling the visibility of components based on user privileges/claims</li><li>Deep discussion about angular router or router guards.</li><li>Discuss the angular application structure and its different components.</li></ul><p>Now we have our goals and expectations set let start creating our claim based authentication.</p><p>To make the development process faster and move straight to the claim-based authorization we are interested in, I have created a skeleton repository that contains the structure of our application and all of its dependencies pre-configured. Clone the repository to the location you want inside your local system by executing.</p><pre>git clone <a href="https://github.com/Mikearaya/angular-authentication-skeleton">https://github.com/Mikearaya/angular-authentication-skeleton</a></pre><p>Once you have successfully cloned the repository navigate inside it and install all of its dependencies by running:</p><pre>npm install</pre><p>This will install all the angular required packages along with bootstrap and all of its dependencies I have used for styling purposes.</p><p>Once the installation completes, serve the application by running:</p><pre>ng serve -o</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IIFDl7nSrAug_c4z1qcGyg.png" /></figure><p>After the compilation process completes a browser window should pop up and you should see something similar to the above image.</p><p>As you can see our application consists of 3 sections home page, user page, admin page sections which we are going to modify and implement the following access control rules.</p><ul><li>Home Page — Should be accessed by all visitors.</li><li>Admin page — Should Only accessible by the admin of the site</li><li>User Page — Should be accessible by system admin and user but not ordinary visitors.</li><li>Unauthorized component — used when an unauthorized user tries to access a certain component</li></ul><p>In the upcoming section, we will see how we can implement the above requirements in our angular application using claim based authorization using angular router guards.</p><p>First, open the source code with your favorite IDE and navigate to <a href="https://github.com/Mikearaya/angular-authentication-skeleton/blob/master/src/app/app-routing.module.ts"><em>src/app/app-routing.module.ts</em></a><em> </em>you can see how the application routes are structured.</p><pre>const routes: Routes = [<br>              {<br>                path: &quot;&quot;,<br>                component: HomePageComponent<br>              },<br>              {<br>                path: &quot;admin&quot;,  <br>                loadChildren: () =&gt; import(&quot;./admin-section/admin-section.module&quot;).then( m =&gt; m.AdminSectionModule )<br>              },<br>              {<br>                path: &quot;user&quot;, loadChildren: () =&gt; import(&quot;./user-section/user-section.module&quot;).then( m =&gt; m.UserSectionModule)<br>              }<br>           ];</pre><p>Each section is implemented as an <a href="https://angular.io/guide/ngmodules">angular module</a>s which are loaded using <a href="https://angular.io/guide/lazy-loading-ngmodules">lazy loading</a>. I’m not going to discuss lazy loading, but if you are interested to learn more about it and why we should use it refer to the official <a href="https://angular.io/guide/lazy-loading-ngmodules">documentation</a>.</p><p>What we want to do now is restrict access to each route based on the current authenticated user’s claims by implementing the angular router guard.</p><p>In order to do that, we need to create a service that will be used to compare claims defined for a route required to access it and claims the user has and return a boolean value accordingly.</p><p>We will call this <em>ServiceSecurity</em> service. But before creating this service lets first define what our claim object will look like by creating a file auth.model.ts inside src/app/auth.model.ts and defining the following interfaces:</p><pre>export class AppUserAuth {<br>               userName = &quot;&quot;;<br>               bearerToken = &quot;&quot;;<br>               isAuthenticated = false;<br>               claims: ClaimModel[] = [];<br> }</pre><pre>export interface ClaimModel {<br>               claimType: string;<br>               claimValue: string;<br> }</pre><p>Here we have created two interfaces that represent our authorization object <em>AppUserAuth</em> and <em>ClaimModel</em>. The <em>AuthObject</em> consists of 4 properties:</p><ul><li><strong><em>userName</em></strong> — Holds the current/logged in users name</li><li><strong><em>bearerToken</em></strong> — Holds the authorization token that will be passed to the application from the server, this is the value we attach to the http|s header property to authenticate our selves to the backend.</li><li><strong><em>isAuthenticated</em></strong> — Used to Verify if the user is authenticated in the system successful</li><li><strong><em>claims[] — </em></strong><em>H</em>old the claims a certain user has, this property is an object consisting of a property <em>claimType</em> &amp; <em>claimValue</em>.</li></ul><p>Now that we have defined our claim object we are ready to generate the service that will operate on this object to verify the validity of users claims:</p><pre>ng generate service SecurityService</pre><p>Since we want to use one instance of the security object make sure the @Injectable modifier contains object <em>{ providedIn: “root” } </em>to tell the angular injector to inject this service at the root level of the component.</p><blockquote>If you want to learn more about angular dependency injection and how it works refer to the official <a href="https://angular.io/guide/dependency-injection">documentation</a></blockquote><p>Define a public property that will hold the <em>AppUserAuth</em> object we have defined above.</p><pre>securityObject: AppUserAuth;</pre><p>make sure to import the AppUserAuth from src/app/auth.model.ts</p><pre>import { AppUserAuth } from &quot;./auth.model&quot;;</pre><p>Next, define a private helper function that will be used to verify if a certain claim is valid or not, it will take two string arguments; <em>claimType</em> which is the claim we want to check the value of and an optional <em>claimValue</em> which can be <em>true</em> or <em>false</em>.</p><p>The <em>claimType</em> can be passed in two ways:</p><ul><li>Only holding the string <em>claimType</em> value eg. ‘<em>canAddUser’</em></li><li>The <em>claimType</em> along with a boolean value separated with a colon ‘:’ eg <em>canAddUser: true.</em></li></ul><p>Let me paste the entire function code at once and we will discuss what each line of code does after it.</p><pre>private isClaimValid(claimType: string, claimValue?: string):boolean {<br>   let ret = false;<br>   let auth: AppUserAuth = null;<br>   auth = this.securityObject;<br>   <br>   if (auth) {<br>      if (claimType.indexOf(&quot;:&quot;) &gt;= 0) {<br>         const words: string[] = claimType.split(&quot;:&quot;);<br>         claimType = words[0].toLocaleLowerCase();<br>         claimValue = words[1];<br>      } else {<br>         claimType = claimType.toLocaleLowerCase();<br>         claimValue = claimValue ? claimValue : &quot;true&quot;;<br>      }</pre><pre>const s = auth.claims.find(c =&gt; c.claimType.toLocaleLowerCase() === claimType &amp;&amp; c.claimValue === claimValue );</pre><pre>ret = auth.claims.find( c =&gt; c.claimType.toLocaleLowerCase() ===    claimType &amp;&amp; c.claimValue === claimValue ) != null;</pre><pre>}</pre><pre>return ret;</pre><pre>}</pre><p>In the beginning, we have defined a few value holder variables. Next, we check if the current user’s security object is defined and proceed further only if that’s true. Inside the if block we check if the passed <em>claimType</em> type is of <em>claimType: value or claimType</em> and extract the <em>claimType</em> &amp; <em>claimValue </em>accordingly.</p><p>After that, we checked if the given claim type exists inside the current user’s claims array — <em>this will be usually stored in local storage when a user first logs in, </em>and return a boolean value accordingly.</p><p>Now that we have defined the private helper function that will parse the claim type to check for validity lets now create a public function that will be called outside of this class by whoever is trying to check for claim validity.</p><p>Let’s call this function <em>hasClaim and it</em> will take 2 arguments one a <em>claimType</em> that can be a string or array and a second optional string argument that will take a <em>claimValue. </em>Like always I will define the whole function and we will go through each line of code afterward.</p><pre>hasClaim(claimType: any, claimValue?: any): boolean {<br>   let ret = false;<br>      <br>     if (typeof claimType === &quot;string&quot;) {<br>        ret = this.isClaimValid(claimType, claimValue);<br>     } else {<br>       const claims: string[] = claimType;<br>          <br>        if (claims) {<br>           for (let index = 0; index &lt; claims.length; index++) {<br>              ret = this.isClaimValid(claims[index]);<br>                if (ret) { break; }<br>           }<br>        }<br>    }<br>   <br>   return ret;<br> }</pre><p>First, since the claim type can be of a string or an array of ClaimModels we checked which form it is. if it’s of a string type we simply pass it to the <em>isClaimValid </em>function to check it’s validity<em> </em>else we loop through each object of <em>claimModel</em> and check it’s validity by passing it to the <em>isClaimValid</em> function, we exit this loop the moment we find a negative result. That pretty much sums up the logic required to validate a certain claim.</p><p>Now that we have completed our service implementation we can move over and create the router guard that will actually implement the authorization security we require.</p><p>In the angular CLI execute the command below to generate the router guard. we will call it AuthGuard.</p><pre>ng generate guard AuthGuard</pre><p>This will prompt us to choose the type of route guard we intend to create.</p><pre>? Which interfaces would you like to implement? (Press &lt;space&gt; to select, &lt;a&gt; to toggle all, &lt;i&gt; to invert selection)<br>❯◯ CanActivate<br> ◯ CanActivateChild<br> ◯ CanLoad</pre><p>Select can <a href="https://angular.io/api/router/CanActivate">CanActivate</a> which is used to prevent activation of a certain component. I’m not going to give you a briefing each Route Guard type and there a difference but if you want to learn more refer to this great <a href="https://alligator.io/angular/route-guards/">article</a> or the official <a href="https://angular.io/guide/router">documentation</a>.</p><p>This will create a router guard that will check a given boolean value before activating a component route.</p><blockquote>Note this will not stop angular from loading the component from the server but only stops it from coming into view. if you want to check the authority of a person before the component is loaded into the browser you can use the <a href="https://angular.io/api/router/CanLoad">canLoad guard</a></blockquote><p>Let’s first inject the services required for the router guard to function which are our custom made service we have defined previously and the Router service from <a href="https://angular.io/api/router">@angular/router</a> package.</p><pre>constructor( <br>private securityService: SecurityServiceService,<br>private router: Router) {}</pre><p>Now let’s implement the logic that will be used to authorize the user access to a certain component. Update the pre-generated <a href="https://angular.io/api/router/CanActivate"><em>canActivate</em></a> function of the router guard with the following code.</p><pre>canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot ):| Observable&lt;boolean | UrlTree&gt; | Promise&lt;boolean | UrlTree&gt; | boolean | UrlTree { <br>    <br>   const claimType: string = next.data[&quot;claimType&quot;];<br>     <br>     if (this.securityService.hasClaim(claimType)) {<br>         return true;<br>     } else {<br>        alert(&quot;Unauthorized Returning User Back to Home Page&quot;);<br>        this.router.navigate([&quot;/&quot;]);<br>     }<br>  <br>  return true;<br>}</pre><p>Inside the <a href="https://angular.io/api/router/CanActivate"><em>canActivate</em></a> function, we have used the <strong><em>next</em></strong> property of the <a href="https://angular.io/api/router/ActivatedRouteSnapshot"><em>ActivatedRouteSnapshot</em></a> property passed to the router to read the data property which will hold the <em>claimType</em> custom property we have not defined yet but will get to it soon. Next, we used the function we defined in our custom security <a href="https://github.com/Mikearaya/angular-authentication-complete/blob/master/src/app/security-service.service.ts"><em>src/app/security-service.service.ts</em></a> to check if the <em>claimType</em> is valid or not.</p><pre>if(this.securityService.hasClaim(claimType))</pre><p>If the claim is valid the <em>canActivate</em> method will return true which will tell the router guard to accept the route request else we will show an unauthorized message and redirect the user to the root route or home directory.</p><p>Finally, we have to update the router configuration to implement our custom route guard we have implemented and define the claims required to access a certain route.</p><pre>const routes: Routes = [<br>               {<br>                  path: &quot;&quot;,<br>                  component: HomePageComponent<br>               },<br>               {<br>                  path: &quot;admin&quot;,<br>                  data: { claimType: &quot;canViewAdminSection&quot; },<br>                  canActivate: [AuthGuardGuard],<br>                  loadChildren: () =&gt; <br>                },<br>                {<br>                  path: &quot;user&quot;,<br>                  canActivate: [AuthGuardGuard],<br>                  data: { claimType: &quot;canViewUserSection:true&quot; },<br>                  loadChildren: () =&gt; <br>          ];</pre><p>As you can see we have updated the router configuration with a <em>canActivate</em> route guard and defined our custom claim value using the <em>data</em> property provided by the router.</p><p>before firing up our application we need to make a few adjustments to our <a href="https://github.com/Mikearaya/angular-authentication-complete/blob/master/src/app/security-service.service.ts"><em>src/app/security-service.service.ts</em></a> to include a method that will enable us to change the current user type along with their respective claims. include the following function inside <a href="https://github.com/Mikearaya/angular-authentication-complete/blob/master/src/app/security-service.service.ts"><em>src/app/security-service.service.ts</em></a></p><pre>logIn(user: string = &quot;&quot;): Observable&lt;AppUserAuth&gt; {<br>    let currentUser;<br>     <br>    if (user.toUpperCase() == &quot;ADMIN&quot;) {<br>         currentUser = AdminClaims;<br>    } else if (user.toUpperCase() == &quot;USER&quot;) {<br>         currentUser = userClaims;<br>    } else {<br>         currentUser = JSON.parse(localStorage.getItem(&quot;userClaims&quot;));<br>    }<br>     localStorage.setItem(&quot;userClaims&quot;,JSON.stringify(currentUser));<br>     this.securityObject = currentUser;</pre><pre>return of&lt;AppUserAuth&gt;(currentUser);</pre><pre>}</pre><p>For now, we have implemented a simple function that will change the user type based on pre-defined dummy objects and return the associated <em>AppUserAuth</em> to the calling function. In reality, this is where we will make an API call to authenticate a user and use that value instead.</p><p>create <a href="https://github.com/Mikearaya/angular-authentication-complete/blob/master/src/app/user-type.model.ts"><em>src/app/user-type.model.ts</em></a> file that will hold our pre-defined user types and claims and copy the following object values inside it.</p><pre>export const userClaims = {<br>       bearerToken: &quot;&quot;,<br>       isAuthenticated: true,<br>       claims: [<br>         { claimType: &quot;canViewUserSection&quot;, claimValue: &quot;true&quot; },<br>        { claimType: &quot;canViewAdminSection&quot;, claimValue:  &quot;false&quot; }<br>       ],<br>      userName: &quot;User&quot;<br>     };</pre><pre>export const AdminClaims = {<br>    bearerToken: &quot;&quot;,<br>    isAuthenticated: true,<br>    claims: [<br>    { claimType: &quot;canViewUserSection&quot;, claimValue: &quot;true&quot; },<br>    { claimType: &quot;canViewAdminSection&quot;, claimValue: &quot;true&quot; }<br>   ],<br>    userName: &quot;Admin&quot;<br>   };</pre><pre>export const UnAuthenticatedUser = {<br>  bearerToken: &quot;&quot;,<br>  isAuthenticated: true,<br>  claims: [<br>    { claimType: &quot;canViewUserSection&quot;, claimValue: &quot;false&quot; },<br>    { claimType: &quot;canViewAdminSection&quot;, claimValue: &quot;false&quot; }<br>   ],<br> userName: &quot;UnAuthenticated&quot;<br> };</pre><p>Make sure you have imported the above objects inside <a href="https://github.com/Mikearaya/angular-authentication-complete/blob/master/src/app/security-service.service.ts">src/app/service-service.service.ts</a></p><pre>import { AdminClaims, userClaims, UnAuthenticatedUser } from &quot;./user-type.model&quot;;</pre><p>Finally, update <em>changeUserType</em> function inside <a href="https://github.com/Mikearaya/angular-authentication-complete/blob/master/src/app/app.component.ts"><em>src/app/app.component.ts</em></a> to use the security service function we just created to change the user type every time we make change using the dropdown, by injecting it inside the constructor.</p><pre>export class AppComponent {<br>   securityObject;<br>  <br>  constructor( private authenticationService: SecurityService) {<br>    this.securityObject = this.authenticationService.securityObject;<br>  }</pre><pre>changeUserType(state: string): void { <br>  this.authenticationService.logIn(state).subscribe(data =&gt; (this.securityObject = data));<br>  }<br>}</pre><p>We are done, if you have followed through the article correctly your application should start with the appropriate authorization implementation configured. make sure you saved everything and start the application by running:</p><pre>ng serve -o</pre><p>Try changing the user type and accessing different sections of the application.</p><p>The final <a href="https://github.com/Mikearaya/angular-authentication-complete/blob/master/src/app/security-service.service.ts"><em>src/app/security-service.service</em></a> and <a href="https://github.com/Mikearaya/angular-authentication-complete/blob/master/src/app/auth-guard.guard.ts">src/app/auth-guard.guard.ts</a> files should look similar to this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/299277d26dbe0196587ef592fa5d464d/href">https://medium.com/media/299277d26dbe0196587ef592fa5d464d/href</a></iframe><p>Now that you know how to lock your application sections using claims-based authorization and router guard go ahead and customize it to your needs.</p><blockquote>In this article, we haven’t touched how we can hide or show buttons and other related elements from view, for that I’m going to create a short article that will be a continuation of this and implement a custom <a href="https://angular.io/guide/attribute-directives">directive</a> to hide and show element from the view. until then feel free to play around with this codebase to understand it further.</blockquote><p>you can find the completed implementation at my <a href="https://github.com/Mikearaya/angular-authentication-complete">GitHub</a> repository.</p><p><strong>Reference</strong></p><ul><li><a href="https://angular.io/docs">Angular official documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=844184f3a029" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mikael-araya-blog/angular-restricting-user-access-using-claim-based-authorization-with-router-guard-844184f3a029">Angular: Restricting User Access Using Claim Based Authorization With Router Guard</a> was originally published in <a href="https://medium.com/mikael-araya-blog">Mikael Araya blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Title Component for Angular Application]]></title>
            <link>https://medium.com/mikael-araya-blog/custom-title-component-for-angular-application-ec4b415e0a66?source=rss----32ee1f0de2f2---4</link>
            <guid isPermaLink="false">https://medium.com/p/ec4b415e0a66</guid>
            <category><![CDATA[dynamic-components]]></category>
            <category><![CDATA[reusable]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[angularjs]]></category>
            <dc:creator><![CDATA[Mikael Araya]]></dc:creator>
            <pubDate>Wed, 29 Jan 2020 16:46:01 GMT</pubDate>
            <atom:updated>2020-01-29T18:23:18.006Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*WksQ9FAcjgH6HgzlC1yzNw.png" /><figcaption><a href="https://www.toptal.com/angular-js/top-18-most-common-angularjs-developer-mistakes">image source</a></figcaption></figure><h3>Dynamic Title Component for Angular Application</h3><p>Almost every application in the world has a title for each view/page that it contains, it gives the user visual confirmation on where they are in the site. Since having a title for our pages is a requirement, the only question is how should we implement it.</p><p>There are two ways we can implement a title for our application. we can hard code each title giving it it’s own CSS (maybe use global CSS) on every single page we have or we can create a dynamic component that will take title inputs dynamically and use that component to handle our page title requirements. the latter method is more interesting since it will encapsulate all the HTML and CSS logic in one place so changing it in the future won’t be a problem.</p><blockquote>What we are going to achieve in this post is create single Angular component that will handle all sites title requirement.</blockquote><p>Even though advanced knowledge of angular is not required, a basic understanding of different angular components &amp; basic angular CLI usage will be useful. in addition, since we are going to utilize the <a href="https://rxjs-dev.firebaseapp.com/api">RxJS</a> library understanding some of the basic operators will useful.</p><p><strong>Prerequisites</strong></p><ul><li><a href="https://angular.io/docs">Angular 8.3.x</a></li><li><a href="https://rxjs-dev.firebaseapp.com/api">RxJS 6.x</a></li></ul><p>To get a sense of what we are going to end up with at the end checkout this stackblitz project I created for this purpose:</p><p><a href="https://stackblitz.com/edit/angular-jkd41p?embed=1&amp;file=src/app/app.module.ts">angular-jkd41p - StackBlitz</a></p><h3>Getting Started</h3><p>After confirming you have all the prerequisites installed and set up correctly on your workstation navigate to the directory you want to create the angular project and create the new project lets call it <em>angular-title</em> using the angular CLI.</p><pre>ng new angular-title</pre><p>This will create the skeleton of our project along with some predefined HTML &amp; CSS. navigate to <a href="https://github.com/Mikearaya/angular-title/blob/master/src/app/app.component.html">src/app/app.component.html</a> and replace all its content with router outlet</p><pre>&lt;router-outlet&gt;&lt;/router-outlet&gt;</pre><p>Before we get into creating the title component lets first create three components that we will use for demonstration purposes. we will call these components <em>PageOne, PageTwo &amp; PageThree</em> for simplicity&#39;s sake.</p><pre>ng generate component PageOne<br>ng generate component PageTwo<br>ng generate component PageThree</pre><p>Next, let&#39;s update the router configuration inside <a href="https://github.com/Mikearaya/angular-title/blob/master/src/app/app-routing.module.ts">src/app/app-routing.module.ts</a> to route URL requests to these components.</p><pre>const routes: Routes = [<br>                         {<br>                           path: &quot;one&quot;,<br>                           component: PageOneComponent,<br>                         },<br>                         {<br>                           path: &quot;two&quot;,<br>                           component: PageTwoComponent<br>                         },<br>                         {<br>                           path: &quot;three&quot;,<br>                           component: PageThreeComponent<br>                         }<br>                      ];</pre><p>Now that we have completed the basic structure of our application, It’s time to create our title component. We will call this <em>angular-title</em> but feel free to name it whatever you want.</p><pre>ng generate component AngularTitle</pre><p>Next, navigate to the newly created component typescript file <a href="https://github.com/Mikearaya/angular-title/blob/master/src/app/angular-title/angular-title.component.ts"><em>src/app/angular-title/angular-title.component.ts</em></a> and start modifying it. first, we will inject all the dependency the component requires as I mentioned previously we are going to utilize angular router built-in functionality and <a href="https://rxjs-dev.firebaseapp.com/api">RxJS</a> operators.</p><blockquote>What is great about angular router module is in addition to routing URL requests to the right components, it enable us to attach extra information using its data property which we will use in the next section to pass the title information for the component</blockquote><p>we will be using two services from angular @angular/router package:</p><ul><li><a href="https://angular.io/api/router/Router"><strong><em>Router</em></strong></a> — A service that provides navigation and URL manipulation capabilities.</li><li><a href="https://angular.io/api/router/ActivatedRoute"><strong><em>ActivatedRoute</em></strong></a> — Provides access to information about a route associated with a component that is loaded in an outlet.</li></ul><p>Let&#39;s go ahead and inject these services in our title component before we can start using them. update the constructor of <a href="https://github.com/Mikearaya/angular-title/blob/master/src/app/angular-title/angular-title.component.ts">src/app/angular-title/angular-title.component.ts </a>with the following code. in addition lets create a property called title to hold the value of the current views title.</p><pre>public title: string;</pre><pre>constructor(private router: Router, private route: ActivatedRoute) {}</pre><p>make sure you have imported the services from their respective npm package</p><pre>import { Router, ActivatedRoute } from &quot;@angular/router&quot;;</pre><p>Next, we are going to start using the service we have injected to extract the information we need from the router to create our dynamic title component. Let me first show you the code we will be writing and we will go through each line of code and discuss what it’s doing. copy and paste the following code inside the <em>ngOnInit</em> function of the AngularTitleComponent component.</p><pre>ngOnInit() {</pre><pre>this.router.events.pipe(filter(event =&gt; event instanceof NavigationEnd)).subscribe(event =&gt; {<br>    let currentRoute = this.route.root;<br>        do {<br>             const childrenRoutes = currentRoute.children;<br>             currentRoute = null;<br>             childrenRoutes.forEach(route =&gt; {<br>             <br>           if (route.outlet === &quot;primary&quot;) {<br>               this.title = route.snapshot.data.title;<br>               currentRoute = route;<br>           }<br>       });<br>    } while (currentRoute);<br>  });<br>}</pre><p>Don’t forget to add <strong><em>NavigationEnd</em></strong> to the import statement of <em>@angular/router</em> and also import filter operator from its respective <a href="https://rxjs-dev.firebaseapp.com/api">RxJS</a> package.</p><pre>import { NavigationEnd, Router, ActivatedRoute } from &quot;@angular/router&quot;;<br>import { filter } from &quot;rxjs/operators&quot;;</pre><p>Lets now dissect each line of code to understand what we are doing. Since we want to grab the title property from the router data property we have used the <em>ngOnInit</em> lifecycle hook for that, next, we used the events property from the router service which emits events on every stage of the router state. Next, we used <em>pipe and filter </em>helper function from <strong><em>RxJS</em></strong> to funnel all the events and get the event we are interested in listening to <a href="https://angular.io/api/router/NavigationEnd"><strong><em>NavigationEnd</em></strong></a> respectively. Afterward, we subscribed to our tailored event which only emits NavigationEnd and start manipulating the data to our needs.</p><p>In the subscription, we capture the root/top of the current router tree and looped through it until the end or current router state. what is important in this section is a notice we are assigning the title by reading the title data from each route configuration.</p><pre>this.title = route.snapshot.data.title;</pre><p>This is reading from the data property I’ve mentioned previously and assigning the title value defined in it.</p><p>The next thing we have to do now is define the title property for each route in the router configuration using the data property provided by Router so that our title component function can read it.</p><pre>const routes: Routes = [<br>                         {<br>                           path: &quot;one&quot;,<br>                           component: PageOneComponent,<br>                           data: {title: &#39;Page One Title&#39;}<br>                         },<br>                         {<br>                           path: &quot;two&quot;,<br>                           component: PageTwoComponent,<br>                           data: {title: &#39;Page Two Title&#39;}<br>                         },<br>                         {<br>                           path: &quot;three&quot;,<br>                           component: PageThreeComponent,<br>                           data: {title: &#39;Page Three Title&#39;}<br>                          }                     <br>                       ];</pre><p>Now that we have finished all the logic required to fetch the title of the current view dynamically let&#39;s create the HTML file that will display the content provided by this class. modify the content of <a href="https://github.com/Mikearaya/angular-title/blob/master/src/app/angular-title/angular-title.component.html">src/app/angular-title/angular-title.component.html</a> with the below code snippet:</p><pre>&lt;h3&gt; {{ title }} &lt;/h3&gt;</pre><p>I haven’t obsessed with how the title is displayed however you can add extra CSS or JavaScript to change how the title is displayed. My main focus is to show you the dynamic title generation aspect, not design suggestion :).</p><p>Our component is ready to use all that is left now is add it in our <a href="https://github.com/Mikearaya/angular-title/blob/master/src/app/app.component.html">src/app/app.component.html</a> file and we are ready to go. additionally, since we need a way to navigate from one page to another let create buttons that will help us do that too</p><pre>&lt;app-angular-title&gt;&lt;/app-angular-title&gt;<br>&lt;router-outlet&gt;&lt;/router-outlet&gt;<br>&lt;button routerLink=&quot;/one&quot;&gt;First Component&lt;/button&gt;<br>&lt;button routerLink=&quot;/two&quot;&gt;Second Component&lt;/button<br>&lt;button routerLink=&quot;/three&quot;&gt;Second Component&lt;/button&gt;</pre><blockquote>Where you put the component is up to your need I’ve put it inside <strong>AppComponent</strong> because i wanted to make it a global title component. if your requirement is different feel free to change it’s location</blockquote><p>Save all the unsaved files in the project and serve it using angular CLI by executing.</p><pre>ng serve -o</pre><p>Congratulation now you know you have another option to implement title in your application. If you are interested in reusable dynamic components you can check out my other articles where I show how you can create<a href="https://medium.com/mikael-araya-blog/reusable-angular-grid-component-using-syncfusions-ejs-angular-grid-d1d2ecca7f99?source=friends_link&amp;sk=8934d7333f63c25aad92d1e9218dc3c3"> dynamic angular grid component </a>and <a href="https://medium.com/mikael-araya-blog/building-clickable-breadcrumbs-component-for-angular-application-584496378215?source=friends_link&amp;sk=4860946a2be59f4640ff0a832f87e0bb"><em>breadcrumb component</em></a>.</p><p>The final code for TitleComponent is shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd0ea96fe8ddcaa4169d031c64159525/href">https://medium.com/media/dd0ea96fe8ddcaa4169d031c64159525/href</a></iframe><p>You can find the source code for this component <a href="https://github.com/Mikearaya/angular-title">here</a>.</p><p><strong>Reference</strong></p><ul><li><a href="https://angular.io/docs">Angular Documentation</a></li><li><a href="https://cli.angular.io/">Angular CLI</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec4b415e0a66" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mikael-araya-blog/custom-title-component-for-angular-application-ec4b415e0a66">Custom Title Component for Angular Application</a> was originally published in <a href="https://medium.com/mikael-araya-blog">Mikael Araya blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Clickable Breadcrumbs Component for Angular Application]]></title>
            <link>https://medium.com/mikael-araya-blog/building-clickable-breadcrumbs-component-for-angular-application-584496378215?source=rss----32ee1f0de2f2---4</link>
            <guid isPermaLink="false">https://medium.com/p/584496378215</guid>
            <category><![CDATA[reusable]]></category>
            <category><![CDATA[angular-router]]></category>
            <category><![CDATA[breadcrumbs]]></category>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Mikael Araya]]></dc:creator>
            <pubDate>Sun, 26 Jan 2020 11:16:01 GMT</pubDate>
            <atom:updated>2020-02-04T19:37:16.735Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*FglcrAUAekHOLcEaPRCx8g.png" /><figcaption><a href="https://ncuillery.github.io/angular-breadcrumb/#/home">image source</a></figcaption></figure><p>you might have noticed a section on websites that show the navigation path of your current location to help you navigate back to any location along the way. the technical term for this is breadcrumbs, you leave a trail/crumb of web links while navigating through the website.</p><p>I am not going into the details of the type of breadcrumbs when to use them &amp; best practices in this article, refer to this <a href="https://usersnap.com/blog/breadcrumbs/">link</a> if you want an in-depth discussion about breadcrumbs or feel free to do your own research. what I will show you in this article is how you can create a single Angular component that handles all breadcrumb related features.</p><p><strong>Prerequisites</strong></p><ul><li><a href="https://nodejs.org/en/">Node.js V10≤</a></li><li><a href="https://angular.io/docs">Angular 8</a></li><li><a href="https://rxjs-dev.firebaseapp.com/guide/overview">rxjs v 6 ≤</a></li></ul><p>Even though advanced knowledge of <a href="https://angular.io/docs">Angular</a> is not required, understanding of the structure, basic usage of <a href="https://cli.angular.io/">angular CLI</a> and how different components of angular interact will be great. In addition, since we will utilize some of the helper function from <a href="https://rxjs-dev.firebaseapp.com/guide/overview">rxjs</a> it will be helpful if you are already familiar with the library. other than that We are not going to use any external dependency outside of angular to create this component, instead we will leverage all the events and properties of <a href="https://angular.io/api/router">angular router</a> to achieve our goal.</p><p>To get a sense of what to expect at the end of this article check out these <a href="https://stackblitz.com/">stackblitz</a> projects I&#39;ve created for demonstration purposes.</p><p><a href="https://stackblitz.com/edit/angular-nuf1m3?ctl=1&amp;embed=1&amp;file=src/app/app.module.ts&amp;hideExplorer=1&amp;hideNavigation=1&amp;view=preview">angular-nuf1m3 - StackBlitz</a></p><p>First open the terminal window and navigate to the location where you want to create the angular project and create the project let call it angular-breadcrumb by executing</p><pre>ng new angular-breadcrumb</pre><p>Navigate to <a href="https://github.com/Mikearaya/angular-breadcrumb/blob/master/src/app/app.component.html"><em>src/app/app.component.html</em></a><em> </em>and replace all the pre-generated HTML code by angular with a router-outlet to display our components while navigating through our application</p><pre>&lt;router-outlet&gt;&lt;/router-outlet&gt;</pre><p>Next, let create all the components we will need for this demonstration at once. we will need to create a navigation tree to show how we can navigate from one component nested inside another component. For that let&#39;s create three-component and call them <strong><em>HomePage, Child, GrandChild </em></strong>they have no use other than a demonstration of breadcrumbs so we will not worry about there content.</p><pre>ng generate component HomePage<br>ng generate component ChildChild<br>ng generate component GrandChild</pre><p>Go to the routing module configuration at <a href="https://github.com/Mikearaya/angular-breadcrumb/blob/master/src/app/app-routing.module.ts">src/app/app-routing.module.ts </a>and update the <em>routes</em> array by defining the routing information to our newly created demonstration components:</p><pre>const routes: Routes = [<br>    {<br>      path: &quot;&quot;,<br>      component: HomePageComponent,<br>               children: [<br>                   {<br>                     path: &quot;child&quot;,<br>                     component: ChildComponent,<br>                         children: [<br>                              {<br>                                path: &quot;grand-child&quot;,<br>                                component: GrandChildComponent<br>                              }<br>                          ]<br>                    }<br>               ]<br>    }</pre><pre>];</pre><p>As you can see from the routing configuration our components are nested inside one another and create a tree-like structure. To understand more about Angular’s routing configuration refer to the official <a href="https://angular.io/guide/router#configuration">documentation</a>.</p><p>Next, go to <a href="https://github.com/Mikearaya/angular-breadcrumb/blob/master/src/app/home-page/home-page.component.html">src/app/home-page/home-page.component.html</a> and add a router outlet that will be used to show all of its descendant components in this case ChildComponent. in addition add a button that will be used to navigate to child component when it’s clicked. here is the code:</p><pre>&lt;p&gt; home page inside view ! &lt;/p&gt;<br>&lt;router-outlet&gt; &lt;/router-outlet&gt;<br>&lt;button type=&quot;button&quot; routerLink=&quot;/child&quot;&gt;Go To Child&lt;/button&gt;</pre><p>We have added a simple text to inform us we are actually viewing homepage component contents. next, we added a router-outlet component, this will be where all the child components will be injected by angular when we navigate through the application. finally, we added a button that will take use to the child component, notice we have a special/angular attribute/directive inside the button element <a href="https://angular.io/api/router/RouterLink"><em>routerLink</em></a>, which is a directive imported with <a href="https://angular.io/api/router/RouterModule"><em>RouterModule</em></a> that will let you link to different part of your application, in our case we are linking it to the child component.</p><p>Repeat the same process to ChildComponent by updating <a href="https://github.com/Mikearaya/angular-breadcrumb/blob/master/src/app/child/child.component.html">src/app/child/child.component.html</a> with the following code:</p><pre>&lt;p&gt; child component inside view &lt;/p&gt;<br>&lt;router-outlet&gt;&lt;/router-outlet&gt;<br>&lt;button type=&quot;button&quot; routerLink=&quot;/child/grand-child&quot;&gt; Go To Grand Child &lt;/button&gt;</pre><p>finally since GrandChild component doesn’t have any child of its own we are not going to put a router-outlet or a navigation button but simply add the following HTML for debugging/confirmation purpose when we are viewing its content.</p><pre>&lt;p&gt; grand child component inside View! &lt;/p&gt;</pre><p>Great we have successfully created an angular application with three components, it’s not a unicorn application yet, but it will be enough to demonstrate angular routing :).</p><p>The moment we have been waiting for, now that we have created the basic structure of angular application with multiple components and functioning navigation between this component, the next step is to create the breadcrumb component that will give the users visual information of their location while they are navigating through the application.</p><p>First let&#39;s create a component named BreadCrumbs:</p><pre>ng generate component BreadCrumbs</pre><p>This is where the magic starts to happen. As I mentioned previously we are not going to use any external dependency outside of angular to create our reusable breadcrumb component, instead, we are going to make use of event and properties provided by the angular router module.</p><p>With that said, go to the newly created breadcrumb component src/app/bread-crmbs/bread-crumbs.component.ts and inject two services provided by <a href="https://angular.io/api/router">@angular/router</a> package namely <a href="https://angular.io/api/router/Router">Router</a> and <a href="https://angular.io/api/router/ActivatedRoute">ActivatedRoute</a> services inside the component constructor:</p><pre>import { Component, OnInit } from &quot;@angular/core&quot;;<br>import { ActivatedRoute, Router} from &quot;@angular/router&quot;;</pre><pre>export class BreadCrumbsComponent implements OnInit {</pre><pre>  constructor(private router: Router, private route: ActivatedRoute){}<br>  ngOnInit() {}</pre><pre>}</pre><p>we have injected the following services</p><ul><li><a href="https://angular.io/api/router/Router">Router</a> — A service that provides navigation and URL manipulation capabilities. <em>we are mainly interested in the </em><a href="https://angular.io/api/router/Router#events"><em>events</em></a><em> event of this service to keep track of the router state of our application.</em></li><li><a href="https://angular.io/api/router/ActivatedRoute">ActivatedRoute</a> — Used to traverse the <a href="https://angular.io/api/router/RouterState">RouterState</a> tree and extract information from nodes.</li></ul><p>Finally lets create a mapping that we will use to record the breadcrumbs of the application navigation. Add this mapping property at the top of the breadcrumbs class.</p><pre>breadcrumbs: Array&lt;{ label: string; url: string }&gt;;</pre><p>lets create one more Input property to take the flexibility of our component a little further.</p><pre>@Input()<br>public deliminator: string = &quot;&gt;&quot;;</pre><p>This will allow the user to change the deliminator used to separate each breadcrumb to whatever they like by passing it to the component.</p><p>Now we are ready to create the bread and butter of our component. Let me show you the code we are going to use first, and then we discuss what each code does afterward. we want to start listening for the router changes as soon as our application starts and our components initialized, for that reason, we will use the angular <a href="https://angular.io/api/core/OnInit">OnInit</a> life cycle hook to execute our code. copy and paste the following code inside ngOnInit function.</p><pre>ngOnInit() {<br>  this.router.events<br>             .pipe(<br>                filter(event =&gt; event instanceof NavigationEnd)).subscribe(event =&gt; {<br>                 this.breadcrumbs = [];<br>                 let currentRoute = this.route.root,<br>                 url = &quot;&quot;;<br>            do {<br>     const childrenRoutes = currentRoute.children; <br>     currentRoute = null;<br>     childrenRoutes.forEach(route =&gt; {<br>         <br>        if (route.outlet === &quot;primary&quot;) {<br>            const routeSnapshot = route.snapshot;<br>            url += &quot;/&quot; + routeSnapshot.url.map(segment =&gt; segment.path).join(&quot;/&quot;);<br>            this.breadcrumbs.push({<br>                          label:route.snapshot.data.breadCrum,<br>                          url: url<br>                           });<br>           currentRoute = route;<br>         }<br>      });</pre><pre>     } while (currentRoute);<br>   });</pre><pre>}</pre><p>We have used the router service we have injected inside the constructor and subscribed to its events property which emits routing events each step of the angular router life cycle. next, we used the <a href="https://rxjs-dev.firebaseapp.com/guide/operators">pipe operator</a> to filter the events emitted from the router to a specific event we want to listen to <a href="https://angular.io/api/router/NavigationEnd">NavigationEnd</a> which is fired each time a navigation cycle ends.</p><blockquote>one thing great about angular router configuration is it enable use to define additional data associated with each route to pass extra information we want to the component, which we will make use of shortly.</blockquote><p>Next, we used the <em>activatedRoute</em> service we have injected inside the constructor to get the root/beginning of the router and store that in a temporary variable. Starting from the root of the route we loop through the route tree and save the URL associated with each level of the tree along with the route’s <em>data</em> property found on each route and reading the breadCrumb property we have defined for this purpose. finally, we save each URL with it’s associated breadcrumb value in the mapping we have created previously, <em>breadCrumbs</em>.</p><p>Now lets update the <a href="https://github.com/Mikearaya/angular-breadcrumb/blob/master/src/app/bread-crumbs/bread-crumbs.component.html">src/app/bread-crumbs/bread-crumbs.component.html </a>to display the breadcrumbs generated by the class.</p><pre>&lt;div&gt;<br>   &lt;span *ngFor=&quot;let breadcrumb of breadcrumbs; let last = last&quot;<br>   &lt;small&gt;<br>      &lt;a [routerLink]=&quot;breadcrumb.url&quot;&gt;{{ breadcrumb.label }}&lt;/a&gt;   &lt;/small&gt;<br>&lt;span *ngIf=&quot;!last&quot;&gt;<br>  &lt;small&gt; {{ deliminator }} &lt;/small&gt;&lt;/span&gt;<br>&lt;/span&gt;<br>&lt;/div&gt;</pre><p>There is nothing complicated about the above HTML, we simply looped through the breadcrumbs generated and assign the URL property to an anchor tags routerLink attribute &amp; display the labels/breadcrumbs adding separator on each iteration.</p><p>finally let&#39;s go back to the Router configuration we have created previously and add a data property that holds the breadcrumb value for each route so we can read it inside our BreadCrumb component class.</p><pre>&lt;app-bread-crumbs [deliminator]=&quot;&#39;/&#39;&quot;&gt;&lt;/app-bread-crumbs&gt;<br>&lt;router-outlet&gt;&lt;/router-outlet&gt;</pre><pre>const routes: Routes = [<br>    {<br>      path: &quot;&quot;,<br>      component: HomePageComponent,<br>      data: { breadCrumb: &quot;Home&quot;}<br>       children: [<br>                   {<br>                     path: &quot;child&quot;,<br>                     component: ChildComponent,<br>                     data: { breadCrumb: &quot;child&quot;}   <br>                      children: [<br>                              {<br>                                path: &quot;grand-child&quot;,<br>                                component: GrandChildComponent,<br>                                data: { breadCrumb: &quot;grand-child&quot;}<br>                               }<br>                          ]<br>                    }<br>               ]<br>    }</pre><pre>];</pre><p>Our component is ready for use all we need to do now is go to <a href="https://github.com/Mikearaya/angular-breadcrumb/blob/master/src/app/app.component.html">src/app/app.component.html</a> and add our component where we want to the breadCrumbs to be displayed.</p><pre>&lt;app-bread-crumbs [deliminator]=&quot;&#39;/&#39;&quot;&gt;&lt;/app-bread-crumbs&gt;<br>&lt;router-outlet&gt;&lt;/router-outlet&gt;</pre><p>That’s it if you compile and serve your project the breadcrumb component should be working perfectly. you can now add CSS and give it a little bit more swag or add additional features you want for your need. what is great about this component is since all our logic relating to breadcrumb is packed in one place we can make a change to it anytime we want with no headache.</p><p>The final breadcrumbs class will look like this. if you want the complete project source file you can find it on my <a href="https://github.com/Mikearaya/angular-breadcrumb.git">GitHub repository</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f73166099be74302314fd2d0722ae71/href">https://medium.com/media/6f73166099be74302314fd2d0722ae71/href</a></iframe><p>In my next article, I’ll show you how we can create an application-wide title component that uses the same logic we used to create the bread crumb component.</p><p>If you are interested in reusable components designs check out my other article where i show how to create <a href="https://medium.com/mikael-araya-blog/reusable-angular-grid-component-using-syncfusions-ejs-angular-grid-d1d2ecca7f99?source=friends_link&amp;sk=8934d7333f63c25aad92d1e9218dc3c3">Reusable angular grid component using syncfusions ejs-angular-grid</a> and <a href="https://medium.com/mikael-araya-blog/building-clickable-breadcrumbs-component-for-angular-application-584496378215?source=friends_link&amp;sk=4860946a2be59f4640ff0a832f87e0bb"><em>breadcrumb component</em></a>.</p><p>Thank you.</p><p><strong>Reference</strong></p><ul><li><a href="https://angular.io/docs">Angular official Documentation</a></li><li><a href="https://github.com/Mikearaya/angular-breadcrumb.git">repository</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=584496378215" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mikael-araya-blog/building-clickable-breadcrumbs-component-for-angular-application-584496378215">Building Clickable Breadcrumbs Component for Angular Application</a> was originally published in <a href="https://medium.com/mikael-araya-blog">Mikael Araya blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reusable angular grid component using syncfusions ejs-angular-grid]]></title>
            <link>https://medium.com/mikael-araya-blog/reusable-angular-grid-component-using-syncfusions-ejs-angular-grid-d1d2ecca7f99?source=rss----32ee1f0de2f2---4</link>
            <guid isPermaLink="false">https://medium.com/p/d1d2ecca7f99</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[syncfusion]]></category>
            <category><![CDATA[grid]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angularjs]]></category>
            <dc:creator><![CDATA[Mikael Araya]]></dc:creator>
            <pubDate>Sun, 26 Jan 2020 04:44:06 GMT</pubDate>
            <atom:updated>2020-01-29T16:27:01.628Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*i69RsjP0_SlZK1c6mUJcAw.png" /></figure><p>Angular is one of the best JavaScript frameworks out there. it has simplified lots of tedious tasks and JavaScript boilerplates for developers since it’s inception. due to its all in one packaging and modular design concept, it’s a preferred choice for large projects and enterprise application.</p><p>We can take angular’s reusable and modular concept and create a custom reusable grid component to have a consistent UI feel throughout our application. In addition, making reusable UI components will ease maintenance and upgrade overhead in the long run.</p><blockquote>Since i’ll provide you with the code that you need every step knowledge of angular is not required but it would be helpful if you have some background knowledge. here is the official <a href="https://angular.io/docs">documentation for angular</a> if you need a brush up before you go to the next stage.</blockquote><p><strong>What we are going to build</strong></p><p>In this article, I’ll show you how you can create a reusable syncfusion angular grid component with most of its boilerplate configurations abstracted in one container component to make it reusable inside other components with little effort.</p><p>you can see the final application on stackblitz to get a sense of what to expect.</p><p><a href="https://stackblitz.com/edit/angular-uckcmd?ctl=1&amp;embed=1&amp;file=src/app/container/container.component.ts&amp;view=preview">angular-uckcmd - StackBlitz</a></p><h4>Environment requirement</h4><ul><li><a href="https://nodejs.org/en/">Node.js</a> version 10.9.0 or later.</li><li>Angular CLI V 8.3.19</li><li>Syncfusion/ejs-angular-grid v 17.4.43</li></ul><p>Once you make sure all the prerequisites are installed properly on your work station navigate to the location you want to create the sample app project in your terminal and create a new angular project, let’s call it <a href="https://github.com/Mikearaya/synfusion_grid_container"><strong><em>synfusion_grid_container</em></strong></a> for convince throughout this article.</p><pre>$ng new syncfusion_grid_container</pre><p>It will ask you if you want routing and the type of stylesheet format you would like to use. enter <strong><em>y</em></strong> and <strong><em>CSS</em></strong> respectively.</p><p>After the above command completes successfully navigate inside the newly created project and run the following <a href="https://cli.angular.io/">A<em>ngular CLI</em></a> command inside the terminal to compile and launch the newly created app.</p><pre>ng serve -o</pre><p>It will automatically open a browser with a page similar to this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZgrIrYe0_NPZQ79r_sV-Pg.png" /><figcaption>default angular startup page</figcaption></figure><p>Next, open the project with your favorite IDE and navigate to <a href="https://github.com/Mikearaya/angular-syncfusion-grid-container/blob/master/src/app/app.component.html"><strong>src/app/<em>app.component.html</em></strong></a><strong><em> </em></strong>and replace all it’s the content inside with angular router outlet component:</p><pre>&lt;router-outlet&gt;&lt;/router-outlet&gt;</pre><p>Now let create our first component using CLI command. In the root directory of the project execute the command.</p><pre>ng new component container</pre><p>Next, we have to update <a href="http://src/app/app-routing.module.ts"><strong><em>src/app/app-routing.module.ts</em></strong></a> routing module to route URL requests to the component we have just created, <em>we will update this line in the future</em> . for now go to <a href="https://github.com/Mikearaya/angular-syncfusion-grid-container/blob/master/src/app/app-routing.module.ts"><strong>src/app/<em>app-routing.module.ts</em></strong></a><strong><em> </em></strong>and update the <em>routes</em> variable to include a path configuration like this.</p><pre>const routes: Routes = [<br>{ path: &quot;&quot;, component: ContainerComponent }<br>];</pre><p>The browser window will refresh and you should see the default content of <strong><em>ContainerComponent </em></strong>displayed.</p><pre>app-container works</pre><p>Now let&#39;s add the <a href="https://www.npmjs.com/"><strong>npm</strong></a> package for <a href="https://ej2.syncfusion.com/angular/documentation/grid/getting-started/?no-cache=1"><strong><em>syncfusion grid</em></strong> </a>and all it’s required dependencies in our workspace by running:</p><pre>npm install --save @syncfusion/ejs-angular-grid</pre><p>This will import syncfusion grid component along with all of its dependencies and update <a href="https://github.com/Mikearaya/angular-syncfusion-grid-container/blob/master/package.json"><strong><em>src/package.json</em></strong></a> file dependency section with the entry of the package.</p><blockquote>For more information about syncfusion grid and how to tweek around it refer to this <a href="https://ej2.syncfusion.com/angular/documentation/grid/getting-started/?no-cache=1">link</a></blockquote><pre>“dependencies”: {<br>        ...<br>       “@angular/router”: “~8.2.14”,<br>       “@syncfusion/ej2-angular-grids”: “^17.4.43”,<br>        ...<br>}</pre><p>Update <a href="https://github.com/Mikearaya/angular-syncfusion-grid-container/blob/master/src/app/app.module.ts"><strong>src/app/<em>app.module.ts</em></strong></a><strong><em> </em></strong>by adding import of <strong>GridModule </strong>and the required service dependencies for it to operate, so we can use it in our application.</p><pre>@NgModule({<br>declarations: [AppComponent, ContainerComponent],<br>imports: [BrowserModule, GridModule, AppRoutingModule],</pre><pre>providers: [<br>            SortService,<br>            FilterService,<br>            GroupService,<br>            EditService,<br>            ExcelExportService,<br>            ColumnChooserService,<br>            ColumnMenuService,<br>            SearchService,<br>            PdfExportService,<br>            ReorderService,<br>            CommandColumnService,<br>            ToolbarService,<br>            ResizeService,<br>            PageService,<br>            ContextMenuService<br>],<br>bootstrap: [AppComponent]</pre><pre>})</pre><p>Let&#39;s also import all CSS used to give the grid it’s the layout. add this import to the projects global CSS file <a href="https://github.com/Mikearaya/angular-syncfusion-grid-container/tree/master/src/styles.css"><strong><em>src/styles.css</em></strong></a></p><pre>@import &#39;../node_modules/@syncfusion/ej2-base/styles/material.css&#39;;  <br>@import &#39;../node_modules/@syncfusion/ej2-buttons/styles/material.css&#39;;  <br>@import &#39;../node_modules/@syncfusion/ej2-calendars/styles/material.css&#39;;  <br>@import &#39;../node_modules/@syncfusion/ej2-dropdowns/styles/material.css&#39;;  <br>@import &#39;../node_modules/@syncfusion/ej2-inputs/styles/material.css&#39;;  <br>@import &#39;../node_modules/@syncfusion/ej2-navigations/styles/material.css&#39;;<br>@import &#39;../node_modules/@syncfusion/ej2-popups/styles/material.css&#39;;<br>@import &#39;../node_modules/@syncfusion/ej2-splitbuttons/styles/material.css&#39;;  <br>@import &#39;../node_modules/@syncfusion/ej2-angular-grids/styles/material.css&#39;;</pre><p>Now that we have set up all the required modules and dependencies we can go ahead and start creating the reusable grid using them. First, replace the content of <a href="https://github.com/Mikearaya/angular-syncfusion-grid-container/blob/master/src/app/container/container.component.ts"><strong><em>src/app/container/container.component.ts</em></strong></a><strong><em> &amp; </em></strong><a href="https://github.com/Mikearaya/angular-syncfusion-grid-container/blob/master/src/app/container/container.component.html"><strong><em>src/app/container/container.component.html</em></strong></a><strong><em> </em></strong>with the content below accordingly then we will discuss what each line of code does one by one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4097e84d7624804cd064448bb9f139fb/href">https://medium.com/media/4097e84d7624804cd064448bb9f139fb/href</a></iframe><p>Next, create a folder named interfaces under <a href="http://src/app/interfaces/"><strong><em>src/app/interfaces</em></strong></a> and create all the custom data model files we have defined below for our container component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f75c4ef8f481e087bc5dc796fd4f571/href">https://medium.com/media/8f75c4ef8f481e087bc5dc796fd4f571/href</a></iframe><p>Now Let&#39;s start by examining all the properties defined the container inside <a href="https://github.com/Mikearaya/angular-syncfusion-grid-container/blob/master/src/app/container/container.component.ts"><strong><em>src/app/container/container.component.ts</em></strong></a> before proceeding to examine the methods.</p><blockquote>Note i have only used few configuration options for demonstration purpose, there are lots of configuration options you can use to customize functionality of the grid. for more information on the range of configuration option visit this <a href="https://ej2.syncfusion.com/angular/documentation/api/grid/">link</a>.</blockquote><p>I used <a href="https://angular.io/api/core/Input">Input</a> data binding to pass data from parent containers that use the component. I’ll explain what each Input property is and what it is used for.</p><ul><li><strong>Input() </strong>columnsList — Array of column definition that defines each column and its type for creating columns dynamically.</li><li><strong>Input()</strong> data— Data we want to be presented from the parent component.</li><li><strong>Input()</strong> showUpdate— shows or hides the update button on the grid</li><li><strong>Input()</strong> showDelete— shows or hides Delete button on the grid</li><li><strong>Input()</strong> showAdd — shows or hides Add button on the grid</li><li><strong>Input()</strong> showPdfExport — shows or hides PDF button on the grid</li><li><strong>Input()</strong> showExcelExport — shows or hides excel export button on the grid</li><li><strong>Input() </strong>showColumnChooser —shows or hides column chooser button on the grid</li><li><strong>Input() </strong>deleteRoute — Used to alter the default route when the delete button is clicked. the <em>default route</em> is <a href="http://current_url/selected_item_id."><strong><em>http|s://current_url/selected_item_id</em></strong>.</a></li><li><strong>Input()</strong> editRoute — Used to alter the default route when edit button is clicked. default is <strong><em>http|s://current_url/selected_item_id/update</em></strong></li><li><strong>Input() </strong>addRoute — Used to alter the default route when add button is clicked. default is <strong><em>http|s://current_url/add</em></strong></li><li><strong>Input() </strong>allowGrouping — enables or disables the grouping functionality.</li></ul><p>I have also defined <a href="https://angular.io/guide/component-interaction"><strong>Output</strong></a> properties/events that will transmit data to the parent container namely:</p><ul><li><strong>Output</strong> dataQueried — Fires every time a query operation occurs inside the grid. it emits the current state of the grid <em>filter, pagination, sorting, page size, grouping</em> in a standard URL query string format.</li><li><strong>Output</strong> rowSelected — fired every time a row is selected either for update or delete operations. it emits ID of the selected row.</li><li><strong>Output </strong>deleteRecord — fired every time the delete button is clicked. it emits ID of the selected row.</li><li><strong>Output()</strong> editRecord — fires every time the edit button is clicked. emits ID of the selected row.</li></ul><p>Now that we have gone through the properties defined, let&#39;s examine the initialization functions that utilize the above input properties to create the desired grid component.</p><ul><li><strong>initilizeCommandColumn()</strong></li></ul><pre>initilizeCommandColumn(): void {</pre><pre>    if (this.showUpdate) {<br>        this.commands.push({<br>              buttonOption: {<br>                  iconCss: &quot;e-icons e-edit&quot;,<br>                  cssClass: &quot;e-flat&quot;,<br>                  click: this.editAction.bind(this)<br>              }<br>              });<br>    }</pre><pre>    if (this.showDelete) {<br>          this.commands.push({<br>               buttonOption: {<br>                  iconCss: &quot;e-icons e-delete&quot;,<br>                  cssClass: &quot;e-flat&quot;,<br>                 click: this.deleteAction.bind(this)<br>                }<br>          });<br>    }</pre><pre>}<br></pre><p>This function defines buttons found inside the command column. it checks to see if the <em>Boolean</em> value of each property <em>(edit &amp; delete) </em>to<em> </em>hide or show each button accordingly by including or skipping it from the commands property of the component.</p><ul><li><strong>initializeToolbar()</strong></li></ul><pre>initializeToolBar(): void {<br>      if (this.showAdd) {<br>            this.toolbar.push({<br>                      text: &quot;Add&quot;,<br>                      prefixIcon: &quot;e-create&quot;,<br>                       id: &quot;add&quot;<br>                    });<br>      }<br>      if (this.showPdfExport) { <br>            this.toolbar.push({<br>                   text: &quot;PdfExport&quot;,<br>                   prefixIcon: &quot;e-Pdf_Export&quot;,<br>                   id: &quot;pdfExport&quot;<br>             });<br>      }<br>      if (this.showExcelExport) {<br>           this.toolbar.push({<br>                 text: &quot;ExcelExport&quot;,<br>                 prefixIcon: &quot;e-Excel_Export&quot;,<br>                 id: &quot;excelExport&quot;<br>           });<br>      }<br>      if (this.showPrint) {<br>           this.toolbar.push({<br>                text: &quot;Print&quot;,<br>                prefixIcon: &quot;e-print&quot;,<br>                id: &quot;print&quot;<br>           });<br>      }</pre><pre>}</pre><p>This function is used to initialize the buttons that will be shown on top of the toolbar. it checks the value of the input properties and shows each button accordingly. mainly display or hide <em>print, pdf export, add , excel export button</em>.</p><p>Next, let&#39;s examine the event emitter/handler functions defined inside the reusable container.</p><ul><li><strong>toolbarClick</strong></li></ul><pre>toolbarClick(args: ClickEventArgs): void {</pre><pre>     switch (args.item.id) {<br>          case &quot;create&quot;:<br>             if (this.addRoute.trim().length === 0 {<br>               this.router.navigate([&quot;add&quot;], { relativeTo: this.activatedRoute });<br>             } else {<br>              this.router.navigate([this.addRoute]);<br>             }<br>           break;<br>          case &quot;pdfExport&quot;:<br>              this.grid.pdfExport();<br>           break;<br>         case &quot;excelExport&quot;:<br>           this.grid.excelExport();<br>          break;<br>         case &quot;print&quot;:<br>            window.print();<br>          break;<br>        }<br>}</pre><p>This function handles the <a href="https://ej2.syncfusion.com/angular/documentation/api/grid/gridModel/#toolbarclick"><em>toolbarClick</em></a> event which is triggered every time a button on the toolbar is clicked. it checks if the selected button is a <em>create, pdfexport, excelExport, print</em><strong><em> </em></strong>and performs the action accordingly by calling the appropriate function of syncfusion grid component.</p><blockquote>add extra if statement to extend the functionality of this function if you want.</blockquote><ul><li><strong>onDataStateChange — </strong>handles <a href="https://ej2.syncfusion.com/angular/documentation/api/grid/gridModel/#datastatechange"><em>dataStateChange</em></a> event triggered when the grid actions such as <em>Sorting, Paging, Grouping,</em> etc… and emits a <a href="https://ej2.syncfusion.com/angular/documentation/api/grid/dataStateChangeEventArgs/"><em>DataStateChangeEventArgs</em></a>. in this function we simply emit <em>dataStateChanged</em> event passing it the same value we get from <a href="https://ej2.syncfusion.com/angular/documentation/api/grid/gridModel/#datastatechange"><em>dataStateChange</em></a><em> </em>event to the parent component.</li><li><strong><em>actionEndHandler — </em></strong>handles <a href="https://ej2.syncfusion.com/angular/documentation/api/grid/gridModel/#actioncomplete"><em>actionComplete</em></a> event Triggered when Grid actions such as <em>sorting, filtering, paging, grouping,</em> etc. are completed. in this handler, we convert the event parameter <a href="https://ej2.syncfusion.com/angular/documentation/api/grid/actionEventArgs/"><em>ActionEventArgs</em></a> to a custom data model <a href="http://src/app/interfaces/query-string.model.ts"><strong><em>Querystring</em></strong></a><strong><em> </em></strong><em>and </em>pass it to the parent container.</li></ul><p>We have examined the <a href="https://github.com/Mikearaya/angular-syncfusion-grid-container/blob/master/src/app/container/container.component.ts"><strong><em>src/app/container/container.component.ts</em></strong></a> file enough,now let&#39;s move on to its counterpart end examine<strong><em> </em></strong><a href="https://github.com/Mikearaya/angular-syncfusion-grid-container/blob/master/src/app/container/container.component.html"><strong><em>src/app/container/container.component.html</em></strong></a> file and what it does.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4097e84d7624804cd064448bb9f139fb/href">https://medium.com/media/4097e84d7624804cd064448bb9f139fb/href</a></iframe><p>As you can see we have assigned all the properties and event handlers we have defined inside <a href="https://github.com/Mikearaya/angular-syncfusion-grid-container/blob/master/src/app/container/container.component.ts"><strong><em>src/app/container/container.component.ts</em></strong></a><strong><em>. </em></strong>what we are interested about is <em>columnsList</em> property which is of type <a href="http://src/app/interfaces/custom-grid-columns.ts"><em>CustomGridModel</em></a> (custom type we have defined) and the process of creating columns dynamically.</p><p>Examine the code closely the line</p><pre>*ngFor=”let column of columnsList”</pre><p>It loops through the columns list the parent has defined and passed as a <em>Input </em>parameter and creates the columns dynamically. next examine the line</p><pre>*ngIf=”commands.length &gt; 0&quot;</pre><p>It checks to see if there are any enrollments in the command property and hides it from display if it doesn’t contain any.</p><p>We have successfully created our reusable container the only thing left is to create a parent container that uses it to present its data. so we are going to do just that. go to your terminal window and create a new component by running</p><pre>ng generate component View</pre><p>update each file of view component with the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c436236c02d1b82cb9c31329119ce2bb/href">https://medium.com/media/c436236c02d1b82cb9c31329119ce2bb/href</a></iframe><p>lets examine each file of view component</p><ul><li><a href="https://github.com/Mikearaya/angular-syncfusion-grid-container/blob/master/src/app/view/view.component.ts"><strong>src/app/view/view.component.ts</strong></a><strong> — </strong>in this file we created few properties that define the mock data we want to present, how it’s structured (it’s columns) and few event handlers <em>dataQueried </em>that simply logs the data emitted to console for demonstration purpose.</li><li><a href="https://github.com/Mikearaya/angular-syncfusion-grid-container/blob/master/src/app/view/view.component.html"><strong><em>src/app/view/view.component.html </em></strong></a><strong><em>— </em></strong>in this file, we have imported <strong><em>app-container </em></strong>component we created previously and passed few properties using input binding namely <em>columnList, data, showDelete, showUpdate </em>and subscribed to one event <em>dataQueried</em></li></ul><p>Next you have to update <a href="https://github.com/Mikearaya/angular-syncfusion-grid-container/blob/master/src/app/app-routing.module.ts"><strong><em>src/app/app-routing.module.ts</em></strong></a> to redirect URL request to the newly created <em>ViewComponent</em> instead of the previous route to <em>ContainerComponent.</em></p><pre>const routes: Routes = [{ path: “”, component: ViewComponent }];</pre><p>if you refresh your browser you should be able to see the grid container we just created in action.</p><p>Congratulation We have successfully created a reusable grid container we can use in the applications that will provide us with a consistent user interface. you can take this further and add additional functionalities that suit your need. you can find the full code base <a href="https://github.com/Mikearaya/angular-syncfusion-grid-container">here</a>.</p><p><strong>Reference</strong></p><ul><li><a href="https://angular.io/docs"><em>Angular official documenation</em></a></li><li><a href="https://cli.angular.io/"><em>Angular CLI official documentation</em></a></li><li><a href="https://ej2.syncfusion.com/angular/documentation/introduction/"><em>Syncfusion Angular official documentation</em></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1d2ecca7f99" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mikael-araya-blog/reusable-angular-grid-component-using-syncfusions-ejs-angular-grid-d1d2ecca7f99">Reusable angular grid component using syncfusions ejs-angular-grid</a> was originally published in <a href="https://medium.com/mikael-araya-blog">Mikael Araya blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>