<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Vojtech Mašek on Medium]]></title>
        <description><![CDATA[Stories by Vojtech Mašek on Medium]]></description>
        <link>https://medium.com/@vmasek?source=rss-f0b1dd251607------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*JuxoGrT9pFRc35m3mrSwhg.png</url>
            <title>Stories by Vojtech Mašek on Medium</title>
            <link>https://medium.com/@vmasek?source=rss-f0b1dd251607------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 18:46:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vmasek/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Integrating Google APIs with Angular]]></title>
            <link>https://medium.com/angular-in-depth/google-apis-with-angular-214fadb8fbc5?source=rss-f0b1dd251607------2</link>
            <guid isPermaLink="false">https://medium.com/p/214fadb8fbc5</guid>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[calendar]]></category>
            <category><![CDATA[google-api]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Vojtech Mašek]]></dc:creator>
            <pubDate>Thu, 24 Oct 2019 17:58:58 GMT</pubDate>
            <atom:updated>2021-04-13T10:14:26.139Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ps66WL6fkiuyNIynuon0Ww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/0*obG_cfMTseFyhi2Y.png" /></figure><blockquote><a href="https://medium.com/angular-in-depth"><strong><em>AngularInDepth</em></strong></a><strong><em> is moving away from Medium. More recent articles are hosted on the new platform </em></strong><a href="https://indepth.dev/angular/"><strong><em>inDepth.dev</em></strong></a><strong><em>. Thanks for being part of indepth movement!</em></strong></blockquote><h3>💡Motivation</h3><p><strong>Task:</strong><em> We need to access/display events of a private google calendar.</em><br><strong>Problem:</strong> <em>You cannot put private calendar into an iframe or query its events using just an API key. </em><br><strong>Requirements:</strong> <em>Compatible with Angular, TypeScript support(service wrappers/classes and data model types)</em><br><strong>Solution: </strong><em>There’s </em><a href="https://github.com/googleapis/google-api-nodejs-client"><em>google-api-nodejs-client</em></a><em> that provides all we need</em></p><blockquote>Google’s officially supported Node.js client library for accessing Google APIs. Support for authorization and authentication with OAuth 2.0, API Keys and JWT is included.</blockquote><p><strong>Now to figure out how to replace that </strong>Node.js<strong> part with </strong>Angular .</p><h3>🛠️Integration</h3><p>Unfortunately, this library is for NodeJS and there is a slight problem integrating it into “Webpack built apps” and which includes Angular as it relies on some of the NodeJS things that don’t exist in Browser. <br>That is not going to stop us as there is a workaround (<a href="https://github.com/googleapis/google-api-nodejs-client/issues/1270#issuecomment-531051355">discussed here</a>).</p><p>First, we need to extend a Webpack build.</p><pre>npm i -D @angular-builders/custom-webpack</pre><p>Then we need to replace the <em>builder</em> in the <strong>angular.json</strong> project architect configuration file, we also include a path to a custom Webpack config in options:</p><pre>&quot;architect&quot;<em>: </em>{<br>  &quot;build&quot;<em>: </em>{<br>    &quot;<strong>builder</strong>&quot;<em>: </em>&quot;<strong>@angular-builders/custom-webpack:browser</strong>&quot;,<br>    &quot;options&quot;<em>: </em>{<br>      <strong>&quot;customWebpackConfig&quot;<em>: </em>{<br>        &quot;path&quot;<em>: </em>&quot;./extra-webpack.config.js&quot;<br>      },</strong><br>      ...<br>    },<br>    ...<br>  },<br>  &quot;serve&quot;<em>: </em>{<br>    &quot;<strong>builder</strong>&quot;<em>: </em>&quot;<strong>@angular-builders/custom-webpack:dev-server</strong>&quot;,<br>    ...<br>  },<br>}</pre><p><em>Explanations can be found in </em><a href="https://github.com/just-jeb/angular-builders/tree/master/packages/custom-webpack#Custom-webpack-dev-server"><em>Angular’s builder docs</em></a><em>.</em></p><h3>🔨The “hack”</h3><p>Now, what is the actual “hack”? We are about to pretend all these things this NodeJS library needs exist in the browser.</p><ol><li>Simulate some of the NodeJS runtime internals like global and Buffer</li><li>We have to mock a few libs that are required in runtime fs, child_process and https-proxy-agent</li></ol><h4>Providing fallbacks for global and Buffer</h4><p>Add the following polyfills under the application imports in your src/polyfills.ts.</p><pre>import * as process from &#39;process&#39;;<br>(window as any).process = process;</pre><pre>import { Buffer } from &#39;buffer&#39;;<br>(window as any).Buffer = Buffer;</pre><p>Don’t forget to install these packages with npm i -D process buffer .</p><p>Put this to your index.html &lt;head&gt; tag. It will get rid of errors related to accessing the global as it substitutes it with the window.</p><pre>&lt;script&gt;<br>  if (global === undefined) {<br>    var global = window;<br>  }&quot;<br>&lt;/script&gt;</pre><h4>Mocking the libraries</h4><pre><em>// extra-webpack.config.js</em></pre><pre>const path = require(&#39;path&#39;);</pre><pre>module.exports = {<br>  resolve: {<br>    extensions: [&#39;.js&#39;],<br>    alias: {<br>      fs: path.resolve(__dirname, &#39;src/mocks/fs.mock.js&#39;),<br>      child_process: path.resolve(<br>        __dirname,<br>        &#39;src/mocks/child_process.mock.js&#39;<br>      ),<br>      &#39;https-proxy-agent&#39;: path.resolve(<br>        __dirname,<br>        &#39;src/mocks/https-proxy-agent.mock.js&#39;,<br>      ),<br>    },<br>  },<br>};</pre><p>An explanation of what’s going on would be that we are telling WebPack to replace one import (file) with another. You can notice we put all the “mock” files to src/mock so it is easier to understand what these files are to our colleagues working on a project.</p><p>The code inside of these mocks is rather simple. We just need to add a few methods that are used but not required, so they can “do” nothing.<br>Both fs andchild_process will look like this.</p><pre><em>// </em>src/mocks/fs.mock.js</pre><pre>module.exports = {<br>  readFileSync() {},<br>  readFile() {},<br>};</pre><p>The https-proxy-agent is even simpler as it can be just<br>module.exports = {};.</p><h3>🔑Setting up the access</h3><ol><li>Create a new GCP project or use an existing one.</li><li>At <a href="https://console.cloud.google.com/">GCP console</a> select your project and go to the Library tab and enable the API you want to use (in our case it is Google Calendar and Analytics)</li><li>Customize your OAuth consent screen (name, restrictions,…)<br>- set all Scopes for Google APIs you need (calendar, analytics, …)</li><li>Create OAuth credentials <br>- needed if when accessing private data (like calendar events or analytics)</li><li>Proceed to Authentication and use the public and private OAuth keys</li></ol><h3>🔓Authentication</h3><p>You can access a lot of public data from API easily with an API key. Things like public calendars, but as long as you need some <strong>private data</strong> (private calendar for example) you will need to authenticate. That can be done via the OAuth client.</p><p>Provide Google’s OAuth2Client in your app.module.ts providers array. It should look like this:</p><pre>{<br>  provide: OAuth2Client,<br>  useValue: <em>new </em>OAuth2Client(</pre><pre>// You get this in <strong>GCP project credentials</strong><br>    <em>environment</em><strong>.</strong>G_API_<strong>CLIENT_ID</strong>,<br>    <em>environment</em><strong>.</strong>G_API_<strong>CLIENT_SECRET</strong>,</pre><pre>// URL where you&#39;ll handle succesful authentication<br>    <em>environment</em><strong>.</strong>G_API_<strong>REDIRECT</strong>,</pre><pre>),<br>},</pre><p>We will be using redirect based auth so next thing is generating auth URL.</p><pre><strong><em>window</em>.</strong>location<strong>.</strong>href = <strong>this.</strong>oauth2Client<strong>.</strong>generateAuthUrl({</pre><pre><em>// &#39;offline&#39; also gets </em><strong><em>refresh_token</em> </strong> <br>  access_type: &#39;offline&#39;,</pre><pre>// put any scopes you need there, <br>  scope: [</pre><pre>    // in the first example we want to read calendar events<br>    &#39;https://www.googleapis.com/auth/calendar.events.readonly&#39;,<br>    &#39;https://www.googleapis.com/auth/calendar.readonly&#39;,</pre><pre>    // in the second example we read analytics data<br>    &#39;https://www.googleapis.com/auth/analytics.readonly&#39;,</pre><pre>  ],<br>});</pre><p>Thanks to refresh_token OAuthClient should be able to handle token exchange even after it is expired so we don’t have to go through google’s Auth screen every hour after token expiration.</p><h3>️⌨️Example usages</h3><p>If you like exploring documentation you visit <a href="https://googleapis.dev/nodejs/googleapis/latest/">google-apis docs</a> or have a look on <a href="https://googleapis.dev/nodejs/googleapis/latest/calendar/classes/Calendar.html">Calendar</a> as it is used in the example below.</p><h4>📅Using the Calendar Service SDK</h4><p><strong>Permissions</strong></p><p>Make sure that the account you are using does have access to the calendar you want to read events from.</p><p><strong>Code Example</strong></p><p>Provide Calendar class with the default auth method, in our case it is OAuth. Extend your app.module.ts providers array with this:</p><pre>{<br>  provide: calendar_v3<strong>.</strong>Calendar,<br>  useFactory: <br>    (auth: OAuth2Client) =&gt; <em>new </em>calendar_v3<strong>.</strong>Calendar({ auth }),<br>  deps: [OAuth2Client],<br>},</pre><p>Now we have access to a complete set of Google calendar API features with a fully typed SDK interface.</p><p>You can get the calendar as you would any other Angular service, have it as a constructor parameter and dependency injection will provide it for you.</p><pre><em>constructor</em>(<br>  <em>private </em>calendar: calendar_v3<strong>.</strong>Calendar,<br>) {}</pre><p>Here is an example of how to get a list of events on some specific calendar. We will also filter only events that are “today” and not deleted/cancelled.</p><pre>this.calendar.events.list({<br>  <em>// required, it is an email, or email like id of a calendar</em><br>  <strong>calendarId</strong>: CALENDAR_ID,</pre><pre><em>// optional, arguments that let you filter/specify wanted events<br>  timeMin: startOfDay(today).toISOString(),<br>  timeMax: endOfDay(today).toISOString(),<br>  showDeleted: false,<br>  singleEvents: true,</em><br>}),</pre><p>You can also perform other tasks such as creating events but don’t forget to require proper scope claims in with your authentication.</p><h4>📊Using the Analytics SDK</h4><p><strong>Setting permissions</strong></p><pre>⮕ Analytics Console ⮕ Admin ⮕ Account column ⮕ User Management ⮕<br>⮕ Select the user ⮕ Activate the &quot;Read &amp; Analyze&quot; checkbox</pre><p><strong>Getting the “View ID”</strong></p><pre>⮕ Analytics Console ⮕ Admin ⮕ View column ⮕ View Settings ⮕<br>⮕ Copy the <strong>&quot;View ID&quot;</strong> number</pre><p><strong>Code Example</strong></p><p>Same as in a previous example, you’ll need a provider. Provide Analytics class with the default auth method. Extend your app.module.ts providers array with this:</p><pre>{<br>  provide: analytics_v3<strong>.</strong>Analytics,<br>  useFactory:<br>    (auth: OAuth2Client) =&gt; <em>new </em>analytics_v3<strong>.</strong>Analytics({ auth }),<br>  deps: [OAuth2Client],<br>},</pre><p>Again you’ll have it ready to be injected by DI to any injectable class.</p><pre><em>constructor</em>(<br>  <em>private </em>analytics: analytics_v3<strong>.</strong>Analytics,<br>) {}</pre><p>This example will get the specified metrics for the desired time range. In this case, we’ll see total page views for the last 30 days.</p><pre><strong>this.</strong>analytics<strong>.</strong>data<strong>.</strong>ga<strong>.</strong>get({<br>  ids: &#39;ga:xxxxxxxxx&#39;, // replace xxxxxxxxx with your <strong>view ID</strong><br>  &#39;start-date&#39;: &#39;30daysAgo&#39;,<br>  &#39;end-date&#39;: &#39;today&#39;,<br>  metrics: &#39;ga:pageviews&#39;,<br>})</pre><h3>📋Conclusion</h3><p>Having a fully typed SDK for an API is a big difference compared to having to find it all in the docs especially the data models. The Auth part of the problem is also taken care of pretty conveniently so it is not a show stopper for people who don’t know how or don’t want to manage that. <br>Overall it is a lot easier to create features when you have the project environment and tools set up just right.</p><p><em>Follow me </em><a href="https://medium.com/@vmasek"><em>here</em></a><em> or on </em><a href="https://twitter.com/VojtechMasek"><em>Twitter</em></a><em> for further reading or updates. Feel free to reach out in case of some questions.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=214fadb8fbc5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/angular-in-depth/google-apis-with-angular-214fadb8fbc5">Integrating Google APIs with Angular</a> was originally published in <a href="https://medium.com/angular-in-depth">Angular In Depth</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Typed translations in Angular]]></title>
            <link>https://medium.com/angular-in-depth/angular-typed-translations-29353f0a60bc?source=rss-f0b1dd251607------2</link>
            <guid isPermaLink="false">https://medium.com/p/29353f0a60bc</guid>
            <category><![CDATA[translation]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[lazy-loading]]></category>
            <category><![CDATA[i18n]]></category>
            <dc:creator><![CDATA[Vojtech Mašek]]></dc:creator>
            <pubDate>Wed, 21 Nov 2018 12:53:24 GMT</pubDate>
            <atom:updated>2020-04-29T21:43:13.110Z</atom:updated>
            <content:encoded><![CDATA[<h4>Translations and i18n using Angular’s dependency injection, TypeScript and lazy-loading</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8M_-rr0b42VCmof-yC-fEw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/0*Fnyb55q2rbl6ZNT5.png" /></figure><blockquote><a href="https://medium.com/angular-in-depth"><strong><em>AngularInDepth</em></strong></a><strong><em> is moving away from Medium. More recent articles are hosted on the new platform </em></strong><a href="https://indepth.dev/angular/"><strong><em>inDepth.dev</em></strong></a><strong><em>. Thanks for being part of indepth movement!</em></strong></blockquote><p>If you have ever had a problem with maintenance of internationalization and translation in your projects, there might be a simple solution for you. If not, then you are pretty satisfied with your current solution, but maybe you’ll realize what can be improved.</p><h4>What people usually do?</h4><p>In most of our projects, we use the <a href="https://github.com/ngx-translate/core">ngx-translate</a> for handling translations. Angular CLI’s i18n does not support runtime translations yet (<a href="https://github.com/angular/angular/issues/16477">issue #16447</a>). Using i18n in a project seems (and usually is) complicated and a lot of developers are stuck with solutions that are not always reliable in long-term.</p><h4>How can we improve?</h4><p>Let’s see what are the basic needs:</p><ul><li>A way to check if all translation files are correct</li><li>A way to check that keys used to access translation are valid</li></ul><p>After some failed concepts on validation tools, we found a <strong>solution</strong>. TypeScript knows all we need and <strong>dependency injection</strong> will provide the way, with just a little bit of <strong>router</strong>’s elegant <strong>lazy-loading</strong>.</p><h3>What to expect</h3><ul><li>Translations have a <strong>type definition</strong> inferred from a default translation</li></ul><pre>export type Translation = typeof en;</pre><ul><li>Translation data are typescript object</li></ul><p>Example translation object</p><ul><li>The translation is<strong> injected </strong>via dependency injection provider</li></ul><p>Example of translation injection and its usage in component and template</p><ul><li>Each site mutation is <strong>lazy loaded</strong> as a <strong>module </strong>that consists of imported wrapped site module (shared for all mutations) and its own i18n stuff.</li></ul><p><strong>Pros</strong></p><ul><li>No missing (untranslated) keys and parts of the application</li><li>A quick way to validate multiple translate files (objects) compatibility</li><li>Type-safe translation — the compiler will tell if something is not in order</li><li>Translation data lazy-loaded with route module</li><li>Instant translation — nothing needs to be dynamically loaded</li><li>No need for in-template impure pipes</li><li>Translation type can be inherited from default translation</li><li>Routes are prefixed with language/i18n abbreviation and can be localized entirely</li><li>Translations can be simple strings, functions with a string literal or any other custom format that you decide to support</li></ul><p><strong>Cons</strong></p><ul><li>A requirement of lazy-loading route modules (if we want the i18n modules and translations lazy-loaded)</li><li>Loading translation dynamically from another source (server) is a bit tricky and require extra steps</li></ul><h3>Minimal setup</h3><p>It is a lot easier to set up on a greenfield project, in future I would even consider creating a schematic for Angular CLI to generate such a project. But for now, there is this 5<strong><em> </em></strong>step setup guide and <a href="https://github.com/vmasek/angular-typed-translations-demo">demo repository</a>.</p><p>If you’d like to see the code first take a look at the demo, and come back for more details. You can also have a quick look and <a href="https://stackblitz.com/github/vmasek/angular-typed-translations-demo"><strong>try it on stackblitz</strong></a>.</p><p><a href="https://stackblitz.com/github/vmasek/angular-typed-translations-demo">StackBlitz</a></p><ol><li><strong>Lazy loading site routes<br></strong>Minimal setup requires lazy-loaded routes only at the <strong>first level</strong>. This will enable your site to have <strong>separate language sections</strong> all using the shared “<em>site</em>” module and separate “<em>site</em>” translation modules for language-specific configuration.<br><em>One of the crucial things is creating site routing it is just a route configured to lazy-load translated site modules.</em></li><li><strong>Wrapping your app into a shared site module</strong><br>Create one “<em>site</em>” module that will contain your whole site. It is basically a module containing all of the stuff necessary for your project views. It covers almost the same role as app.module.ts had, with the exception that it is not bootstrapped but imported in language specific “<em>site</em>” modules.</li><li><strong>Internationalization </strong>(i18n)<strong><br></strong>Create one module for each translation you want. Each has a separate file (module) and can be easily added later so don’t bother by creating all of them now. Just pick one or two so you can have a working demo soon.</li><li><strong>Translations</strong><br>The translation file itself is just a basic TS file with a constant object. The amazing thing about this over classic JSON is that we can define properties that are any type-able value. Usually, they are string or key-value pair nested object, but they also can be a function handling a specific use case.</li><li><strong>Using translation data</strong><br>Inject the translation data in the constructor and they should now be available for usage in both component and template.</li></ol><p>After each big step, we should verify everything is in order, so we eliminate the problems when they started. At this point, you should be able to load your application same as before but routing/en/my-route and /cs/my-route should have different languages loaded.</p><h3>Network lazy-loaded modules</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*zlmfjJHQFP0dKT9N7cvr9w.gif" /><figcaption>Demo of lazy-loaded i18n modules</figcaption></figure><h3>Interpolation, plurals and message formatting</h3><p>Imagine classic interpolation scenario You need to do {{n}} to unlock this or plurals both can be handled pretty easily with code and for each language separately.</p><p>If the project does not require advanced concepts of custom messages, using a function for interpolation/plural is easy and hackable.</p><pre>// Instead of generic message `Supported languages: ${n}`,<br>// we can have this custom message<br>(n: <em>number</em>) =&gt; `Demo supports ${n} language${n === 1 ? &#39;&#39; : &#39;s&#39;}.`,</pre><p>If this is not enough, it is easy to integrate support for the <a href="http://userguide.icu-project.org/formatparse/messages">ICU message format</a>. There are multiple implementations in JavaScript and all you need is a formatting string that will be passed to render function along with parameters.</p><h3>Intellisense and auto-completion IDE support</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*SOkStFwUsf8hdPUj1H--2g.png" /><figcaption>Intellisense for translations (WebStorm)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*JGzWeZH3d3Aw357efZzcYg.png" /><figcaption>Auto-completion of the available translation values (VS Code)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*VaAp7jytWHV1zqhl_B4n8g.png" /><figcaption>Type is supported even in a template (VS Code)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*PAwefcC5U344PYvzzdNcTg.png" /><figcaption>Help with inherited type interface and error for an invalid key (VS Code)</figcaption></figure><h3>Validation and compilation</h3><p>All errors and inconsistencies in translations are caught at compile time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*eqYGJ20cY7b3l8nv1kR1uw.png" /><figcaption>Error after adding subtitle to only one of the translations</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mGF5hQeKWbFp2f1WOhtI9Q.png" /><figcaption>Error when trying to access non-existing translation with an invalid key</figcaption></figure><h3>Advanced concepts</h3><p>There are potential improvements available for some more advanced concepts that are not currently built into this setup but could be later included. Few to mention are:</p><ul><li>Localized routing (translated routes)</li><li>Internationalization by region (country) instead of the translation</li><li>Splitting translations to multiple lazy-loaded files</li></ul><h3>Conclusion</h3><p>It seems like we managed to cover all of the requirements we defined at the beginning. This solution was tested on multiple projects, even with the server side rendering via universal and so far no issues were found.</p><p>Try it out yourself on this small example project. In case of some questions on this topic feel free to ask in comments.</p><ul><li><a href="https://stackblitz.com/github/vmasek/angular-typed-translations-demo">StackBlitz</a></li><li><a href="https://github.com/vmasek/angular-typed-translations-demo">vmasek/angular-typed-translations-demo</a></li></ul><p><strong><em>PS:</em></strong><em> As it may require a little more steps if the project already uses some translations, I will be posting a migration guide for projects using ngx-translate. Follow me </em><a href="https://medium.com/@vmasek"><em>here</em></a><em> or on </em><a href="https://twitter.com/VojtechMasek"><em>twitter</em></a><em> for updates.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29353f0a60bc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/angular-in-depth/angular-typed-translations-29353f0a60bc">Typed translations in Angular</a> was originally published in <a href="https://medium.com/angular-in-depth">Angular In Depth</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Structural directives in Angular]]></title>
            <link>https://itnext.io/angular-structural-directives-b54ea21b39a7?source=rss-f0b1dd251607------2</link>
            <guid isPermaLink="false">https://medium.com/p/b54ea21b39a7</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular-directive]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Vojtech Mašek]]></dc:creator>
            <pubDate>Tue, 07 Aug 2018 15:43:38 GMT</pubDate>
            <atom:updated>2019-10-25T12:23:53.872Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T4xoFa_YMc6A4ah9ZXdStg.png" /></figure><blockquote><a href="https://angular.io/guide/structural-directives#what-are-structural-directives">Are responsible for HTML layout. They shape or reshape the DOM’s <em>structure</em>, typically by adding, removing, or manipulating elements.</a></blockquote><p>Structural directives are a key part of Angular everyone should be familiar with. They are responsible for manipulating DOM through adding, removing or changing the elements. Even if you have never written a structural directive yourself, you have probably been using <em>*ngIf</em> and <em>*ngFor</em> in your templates pretty often. The asterisk ( * ) states it is a structural directive. If you want to read more before proceeding to our examples, <a href="https://angular.io/guide/structural-directives">angular docs</a> provide a nice, detailed explanation.</p><p>Writing a structural directive is really easy, as we will see in the examples below. Its purpose can vary from simple conditional rendering (e.g. based on user role) to iteration over a range or in-template let-variable declaration.</p><h3>Basics</h3><h4>Manipulating the DOM</h4><p>For a directive to be able to manipulate the DOM, it is necessary to provide a way to do it without actually changing something via DOM API. In Angular, it is done by injecting a view container reference and a template reference to the directive.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7085ff95258f6f2be98a1d26a83ad6af/href">https://medium.com/media/7085ff95258f6f2be98a1d26a83ad6af/href</a></iframe><h4>View Container reference</h4><blockquote>Represents a container where one or more Views can be attached.</blockquote><p>It basically allows us to manipulate the container (outer element wrapper) and attach templates created inside of the directive. More is described in its <a href="https://angular.io/api/core/ViewContainerRef">docs</a>.</p><h4>Template reference</h4><blockquote>Represents an Embedded Template that can be used to instantiate Embedded Views.</blockquote><p>In plain English, it is an element that we’ve put the directive on. We need this reference in the directive because we almost always use the template in some way, either by repeating it (<em>*ngFor</em>), conditionally displaying it (<em>*ngIf</em>) or attaching another element to it on hover (<em>matTooltip</em>).</p><h4>Value input</h4><p>In most cases, we input some value into the directive so it can be used internally. For example, a collection to iterate over, a condition to evaluate or a value to be used for a more specific purpose. The digest cycle of the directive is tied also to the value change, so each time it changes, the directive is reevaluated.</p><p>It isn’t always necessary to input the values; services or state store can be injected and the directive can access the values the same way a component would.</p><h3>Context</h3><p>Every directive has its own context. It is a good practice to define the context as an interface for every directive, so it is understandable what values we expose. This context is then used as a type for the <em>template reference</em> and the properties are set when creating an embedded view on the <em>container reference</em>.</p><h4>Exposing the internal values</h4><p>There are two possible ways to expose the internal values so we can use them in a template: one is naming the variables in the structure and the other is emitting an implicit value.</p><p>For example, the <em>*ngFor</em> directive iterates through the list (array), set properties in its context object and exposes the current item. Exposed values can be used in the template inside the directive-decorated element’s scope.</p><p>In <em>*ngFor</em> there are currently <a href="https://github.com/angular/angular/blob/master/packages/common/src/directives/ng_for_of.ts#L30...L42"><em>index</em>, even, <em>odd</em>, <em>first</em>, <em>last</em></a> context variables exported via their names and one implicit variable representing the current item that we can name as we desire to. In the example below, it’s <em>hero.</em> It should be assigned to contexts <em>$implicit</em> property.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G2tGR4VZSuW8TFdm7US9BA.png" /><figcaption>Usage of the variables exposed from *ngFor directive</figcaption></figure><h3><strong>Let directive</strong></h3><p>If you’ve adopted the usage of async pipe in your templates, you have probably stumbled upon a use case where you would write something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fN5KOBS0uwU6D-dbdolyew.png" /><figcaption>Using the async pipe to get the current value of the user$ data stream and assigning it to user variable</figcaption></figure><p>It allows you to reuse/share the value in the variable you’ve created with “<em>as”</em> syntax. It is really useful if you don’t want to use async pipe multiple times because it creates a subscription on each usage.</p><p>The <em>*ngIf</em> directive serves two purposes there. One is letting us create the variable for async value and the other is hiding/not rendering this whole section if the value is <a href="https://developer.mozilla.org/en-US/docs/Glossary/Falsy">falsy (<em>false, undefined</em>, <em>null</em>, <em>0</em>,…)</a>.</p><p>But what if we want the value even if it is “falsy”? We can take advantage of let directive.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/728b4cc9143b4161845255a0a7431be3/href">https://medium.com/media/728b4cc9143b4161845255a0a7431be3/href</a></iframe><p>Let directive’s context has two properties (as described in its docs). Both of those properties are then used with different syntax they enable for template variable declaration in the usage example’s HTML template.</p><p>Some might say that we should handle these cases with else statement within the <em>*ngIf</em> and yes, it is a perfectly valid solution for most of the cases. The good use-case is handling the falsy values with some sort of custom messages. But not always you want or can separate logic for falsy and <a href="https://developer.mozilla.org/en-US/docs/Glossary/Truthy">truthy</a> values in template, so using a directive like this could make the template a lot simpler and readable.</p><h3>For each of range directive</h3><p>Iterating in templates sometimes requires various things. One of them is having an option to easily display some given number of elements. A good example is the drop-down of numeric values either for table pagination or year select, which can be easily done using it like in the example below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fee1b7d4c6676d1716e76907cea38316/href">https://medium.com/media/fee1b7d4c6676d1716e76907cea38316/href</a></iframe><h3>Code examples repository</h3><p>All examples, usages and source code is at the link below.</p><p><a href="https://github.com/vmasek/ng-beer-directives">vmasek/ng-beer-directives</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FTBcAXgsVFtM%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DTBcAXgsVFtM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FTBcAXgsVFtM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d6b9d4c4d7723777b0d8f6693b56f8c/href">https://medium.com/media/5d6b9d4c4d7723777b0d8f6693b56f8c/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b54ea21b39a7" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/angular-structural-directives-b54ea21b39a7">Structural directives in Angular</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>