<?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 Thomas Rundle on Medium]]></title>
        <description><![CDATA[Stories by Thomas Rundle on Medium]]></description>
        <link>https://medium.com/@ct7?source=rss-168b2940d972------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NQ5D21nHKSlWqhkwEE9LQQ.jpeg</url>
            <title>Stories by Thomas Rundle on Medium</title>
            <link>https://medium.com/@ct7?source=rss-168b2940d972------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 00:47:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ct7/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[A short step-by-step guide for basic Angular 2 routing]]></title>
            <link>https://medium.com/@ct7/a-short-step-by-step-guide-for-basic-angular-2-routing-f403dc0d6b51?source=rss-168b2940d972------2</link>
            <guid isPermaLink="false">https://medium.com/p/f403dc0d6b51</guid>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Thomas Rundle]]></dc:creator>
            <pubDate>Wed, 30 Nov 2016 03:06:28 GMT</pubDate>
            <atom:updated>2016-11-30T03:08:56.521Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a short guide intended to help you quickly get up and running with the Angular 2 router. It’s more concise and procedural than the routing documentation on <a href="http://angular.io/">angular.io</a>, but less comprehensive. I will write follow up articles on routing in Angular 2 expanding on this basic setup.</p><p>The workflow I use for setting up my routing on new Angular 2 project is as follows:</p><ol><li>Add &lt;base&gt; to index.html.</li><li>Create routing for the root module.</li><li>Add links to activate defined paths using <em>RouterLink.</em></li><li>Catch invalid paths.</li><li>Review route order.</li><li>Setup routing for feature modules.</li><li>Optionally, move <em>RouterModule(s) </em>into separate files<em>.</em></li></ol><h3>Step-by-step guide</h3><p><strong>(1) Add &lt;base&gt; to index.html.</strong></p><p>Add &lt;base href=&quot;/&quot;&gt; to <em>index.html </em>as the first child to &lt;head&gt;.</p><pre>&lt;!-- index.html --&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    <strong>&lt;base href=&quot;/&quot;&gt;</strong><br>    &lt;title&gt;Project Manager&lt;/title&gt;<br>...</pre><p><strong>(2) Create routing for the root module.</strong></p><p>Import <em>RouterModule </em>from @angular/router and add it to the @NgModule({..}) imports array in your root module — <em>AppModule.</em></p><p>Then, setup basic routes, defining each path and the component that path <br>will render.</p><pre>// app.module.ts<br>...<br><strong>import { RouterModule } from &#39;</strong><a href="http://twitter.com/angular/router"><strong>@angular/router</strong></a><strong>&#39;;</strong><br>...</pre><pre><a href="http://twitter.com/NgModule">@NgModule</a>({<br>  imports:      <br>   [ <br>    BrowserModule,<br>    <strong>RouterModule.forRoot([<br>      {<br>        path: &#39;projects&#39;,<br>        component: ProjectCenterComponent<br>      },<br>      {<br>        path: &#39;personnel&#39;,<br>        component: PersonnelManagerComponent<br>      },<br>      {<br>        path: &#39;&#39;,<br>        redirectTo: &#39;/personnel&#39;,<br>        pathMatch: &#39;full&#39;<br>      }<br>    ])</strong>,<br>    ...<br>  ],<br>  declarations: [ AppComponent ],<br>  bootstrap:    [ AppComponent ]<br>})<br>export class AppModule { }</pre><p><strong>(3) Add links to activate the defined paths using <em>RouterLink.</em></strong></p><pre>&lt;!-- core/navbar.component.html --&gt;</pre><pre>&lt;nav class=&quot;navbar navbar-inverse navbar-fixed-top&quot;&gt;<br>    &lt;div class=&quot;container-fluid&quot;&gt;<br>        &lt;div class=&quot;navbar-header&quot;&gt;<br>            &lt;a class=&quot;navbar-brand&quot;&gt;Project Manager&lt;/a&gt;<br>        &lt;/div&gt;<br>        &lt;ul class=&quot;nav navbar-nav&quot;&gt;<br>            &lt;li&gt;<br>                &lt;a <strong>routerLink=&quot;/personnel&quot;</strong>&gt;Personnel&lt;/a&gt;<br>            &lt;/li&gt;<br>            &lt;li&gt;<br>                &lt;a <strong>routerLink=&quot;/projects&quot;</strong>&gt;Projects&lt;/a&gt;<br>            &lt;/li&gt;<br>        &lt;/ul&gt;<br>    &lt;/div&gt;<br>&lt;/nav&gt;</pre><p>If your navigation menu is incorporated into a separate module, import <em>RouterModule </em>into the module containing your menu. Otherwise, <em>RouterLink </em>will not be recognized in your template.</p><pre>// core/core.module.ts<br>...<br><strong>import { RouterModule } from &#39;</strong><a href="http://twitter.com/angular/router"><strong>@angular/router</strong></a><strong>&#39;;</strong><br>...<br><a href="http://twitter.com/NgModule">@NgModule</a>({<br>    imports: [ CommonModule, <strong>RouterModule </strong>],<br>    declarations: [ NavbarComponent ],<br>    exports: [ NavbarComponent ],<br>    providers: []<br>})<br>export class CoreModule { }</pre><p>Use <em>RouterLinkActive </em>to apply a class to a link when it’s path is active.</p><pre>// core/navbar.component.html<br>...<br>            &lt;li <strong>routerLinkActive=&quot;active blue&quot;</strong>&gt;<br>                &lt;a routerLink=&quot;/personnel&quot;&gt;Personnel&lt;/a&gt;<br>            &lt;/li&gt;<br>            &lt;li <strong>routerLinkActive=&quot;active blue&quot;</strong>&gt;<br>                &lt;a routerLink=&quot;/projects&quot;&gt;Projects&lt;/a&gt;<br>            &lt;/li&gt;<br>...</pre><p>Note you can apply more than one class to an active link. For demonstration purposes, this activates the class <em>blue </em>as well as the <em>active </em>Bootstrap class. See the styling in the component TypeScript file.</p><pre>// core/navbar.component.ts<br>import { Component } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;</pre><pre><a href="http://twitter.com/Component">@Component</a>({<br>    selector: &#39;ct-navbar&#39;,<br>    templateUrl: &#39;app/core/navbar.component.html&#39;,<br>    styles: [`<br>        .blue  a {<br>            background-color: blue !important;<br>        }<br>    `]<br>})<br>export class NavbarComponent { }</pre><p>The running app now has functional routing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*emhPdlBU3FVDDGgsH93Gmw.gif" /></figure><p><strong>(4) Catch invalid paths.</strong></p><p>Since we don’t want an invalid path to crash our Angular 2 app, we create a <em>NotFoundComponent </em>that will render when a particular path isn’t found.</p><pre>// core/not-found.component.ts<br>import { Component } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;</pre><pre><a href="http://twitter.com/Component">@Component</a>({<br>    template: `<br>        &lt;div class=&quot;container-fluid&quot;&gt;<br>            &lt;div class=&quot;page-header&quot;&gt;<br>                &lt;h1&gt;Path not found&lt;/h1&gt;<br>            &lt;/div&gt; <br>        &lt;/div&gt;<br>    `    <br>})<br>export class NotFoundComponent { }</pre><p>Add a path defined as <em>**. </em>This is the wildcard operator that will match <br>any path. It’s important that this is the last route listed.</p><p>Angular 2 checks for matching routes in the order they are listed. When a route path is matched, Angular 2 renders the component associated with the path and does not check any route beyond it. Therefore, the router will use this wildcard route if no route declared in a lower array index matched the target path.</p><pre>// app.module.ts<br>...<br><a href="http://twitter.com/NgModule">@NgModule</a>({<br>  imports:      <br>    [ <br>      BrowserModule,<br>      RouterModule.forRoot([<br>        {<br>          path: &#39;projects&#39;,<br>          component: ProjectCenterComponent<br>        },<br>        {<br>          path: &#39;personnel&#39;,<br>          component: PersonnelManagerComponent<br>        },<br>        {<br>          path: &#39;&#39;,<br>          redirectTo: &#39;/personnel&#39;,<br>          pathMatch: &#39;full&#39;<br>        }<strong>,<br>        {<br>          path: &#39;**&#39;,<br>          component: NotFoundComponent<br>        }</strong><br>      ]),<br>...</pre><p>Now we handle invalid paths gracefully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zRmJf7qEVIg9lf42cVDIhw.gif" /></figure><p><strong>(5) Review route order.</strong></p><p>Note that the route order is important. Angular Router renders the component for the first path match it encounters.</p><p>Try setting the wildcard route matching the <em>NotFoundComponent</em> as the first route. Reloading the app, you will see that every input path renders the <em>NotFoundComponent.</em></p><p><strong>(6) Setup routing for feature modules.</strong></p><p>Each feature module can have it’s own routing. Import the <em>RouterModule </em>into the feature’s <em>@NgModule({..})</em> and attach <em>Routes </em>to it using <em>RouterModule.forChild()</em>.</p><p>Note that these routes will be siblings of the <em>Routes </em>included in <em>RouterModule.forRoot() </em>on the<em> AppModule. </em>They are not child routes even though the syntax seems to imply that they are.</p><p>Refactor previously setup routes into separate modules like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OzCNf183ioZLqNxOQWU1ZA.png" /></figure><pre>// personnel-manager/personnel-manager.module.ts<br>import { NgModule } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;<br><strong>import { RouterModule } from &#39;</strong><a href="http://twitter.com/angular/router"><strong>@angular/router</strong></a><strong>&#39;;</strong><br>...<br><a href="http://twitter.com/NgModule">@NgModule</a>({<br>    imports: [ <br>        SharedModule,<br>        <strong>RouterModule.forChild([<br>            {<br>                path: &#39;personnel&#39;,<br>                component: PersonnelManagerComponent<br>            },<br>            {<br>                path: &#39;&#39;,<br>                redirectTo: &#39;/personnel&#39;,<br>                pathMatch: &#39;full&#39;<br>            }<br>        ])</strong><br>      ],<br>    ...<br>})<br>export class PersonnelManagerModule { }</pre><pre>// project-center/project-center.module.ts<br>import { NgModule } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;<br><strong>import { RouterModule } from &#39;</strong><a href="http://twitter.com/angular/router"><strong>@angular/router</strong></a><strong>&#39;;</strong><br>...<br><a href="http://twitter.com/NgModule">@NgModule</a>({<br>    imports: [ <br>        SharedModule,<br>        <strong>RouterModule.forChild([<br>            {<br>                path: &#39;projects&#39;,<br>                component: ProjectCenterComponent<br>            }<br>        ])</strong> <br>      ],<br>    ...<br>})<br>export class ProjectCenterModule { }</pre><p>The <em>AppModule </em>now only contains the wildcard route. With this setup, Angular 2 will match the feature module routes before checking the routes at the root module; therefore, our navigation will still work the way we expect.</p><pre>// app.module.ts<br>...<br><a href="http://twitter.com/NgModule">@NgModule</a>({<br>  imports:      <br>    [ <br>      BrowserModule,<br>      <strong>RouterModule.forRoot([<br>        {<br>          path: &#39;**&#39;,<br>          component: NotFoundComponent<br>        }<br>      ])</strong>,<br>      ...<br>})<br>export class AppModule { }</pre><p><strong>(7) Optionally, move <em>RouterModule(s) </em>into separate files<em>.</em></strong></p><p>This is a design choice, and personally, I prefer to keep my routing in a separate file. This becomes useful when the app expands and routing logic becomes complex.</p><pre>// app-routing.module.ts<br>import { NgModule } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;<br>import { RouterModule, Routes } from &#39;<a href="http://twitter.com/angular/router">@angular/router</a>&#39;;</pre><pre>import { NotFoundComponent } from &#39;./core/not-found.component&#39;;</pre><pre>const appRoutes: Routes = [<br>  { path: &#39;**&#39;, component: NotFoundComponent }<br>];</pre><pre><a href="http://twitter.com/NgModule">@NgModule</a>({<br>  imports: [<br>    RouterModule.forRoot(appRoutes)<br>  ],<br>  exports: [<br>    RouterModule<br>  ]<br>})<br>export class AppRoutingModule { }</pre><p>Add <em>AppRoutingModule</em> to the imports in <em>AppModule</em>, replacing the previous <em>RouterModule </em>implementation. Include the <em>AppRoutingModule </em>after the imports of your feature modules.</p><p>Having the <em>AppRoutingModule</em> as the last import item ensures that the feature module routes will be checked first.</p><pre>// app.module.ts<br>...<br><strong>import { AppRoutingModule } from &#39;./app-routing.module&#39;;</strong><br>...<br><a href="http://twitter.com/NgModule">@NgModule</a>({<br>  imports:      <br>    [ <br>      BrowserModule,<br>      CoreModule,<br>      ProjectCenterModule,<br>      PersonnelManagerModule,<br>      <strong>AppRoutingModule</strong><br>    ],<br>  declarations: [ AppComponent ],<br>  bootstrap:    [ AppComponent ]<br>})<br>export class AppModule { }</pre><p>Refactor the routing in the feature modules as well, separating routing into its own file for each feature.</p><pre>// personnel-management/personnel-routing.module.ts</pre><pre>import { NgModule } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;<br>import { RouterModule, Routes } from &#39;<a href="http://twitter.com/angular/router">@angular/router</a>&#39;;</pre><pre>import { PersonnelManagerComponent } from &#39;./personnel-manager.component&#39;;</pre><pre>const personnelRoutes: Routes = [<br>    {<br>        path: &#39;personnel&#39;,<br>        component: PersonnelManagerComponent<br>    },<br>    {<br>        path: &#39;&#39;,<br>        redirectTo: &#39;/personnel&#39;,<br>        pathMatch: &#39;full&#39;<br>    }<br>];</pre><pre><a href="http://twitter.com/NgModule">@NgModule</a>({<br>  imports: [<br>    RouterModule.forChild(personnelRoutes)<br>  ],<br>  exports: [<br>    RouterModule<br>  ]<br>})<br>export class PersonnelRoutingModule { }</pre><pre>// personnel-manager/personnel-manager.module.ts</pre><pre>...<br><strong>import { PersonnelRoutingModule } from &#39;./personnel-routing.module&#39;;</strong><br>...<br><a href="http://twitter.com/NgModule">@NgModule</a>({<br>    imports: [ <br>        SharedModule,<br>        <strong>PersonnelRoutingModule</strong><br>      ],<br>    ...<br>})<br>export class PersonnelManagerModule { }</pre><p>Routing is now ready to scale. Running the app, we see the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yxfDZ2dg0yjtFh9eqh-9Dw.gif" /></figure><p>Thank you for reading. If you found this article useful, please like it.</p><p>I’ve written other articles on Angular 2 including:</p><ul><li><a href="https://medium.com/@ct7/angular2-module-architecture-and-example-seed-project-35b7410264f5">Angular2: Module architecture and example seed project</a></li><li><a href="https://medium.com/@ct7/building-a-reusable-table-layout-for-your-angular-2-project-adf6bba3b498">Building a reusable table layout for your Angular 2 project</a></li><li><a href="https://medium.com/@ct7/the-simple-way-to-make-a-mobile-angular-2-bootstrap-navbar-without-jquery-d6b3f67b037b#.fmyngx546">The simple way to make a mobile Angular 2 Bootstrap navbar without jQuery</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f403dc0d6b51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The simple way to make a mobile Angular 2 Bootstrap navbar without jQuery]]></title>
            <link>https://medium.com/@ct7/the-simple-way-to-make-a-mobile-angular-2-bootstrap-navbar-without-jquery-d6b3f67b037b?source=rss-168b2940d972------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6b3f67b037b</guid>
            <category><![CDATA[bootstrap]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Thomas Rundle]]></dc:creator>
            <pubDate>Tue, 29 Nov 2016 00:19:25 GMT</pubDate>
            <atom:updated>2016-11-29T00:19:25.193Z</atom:updated>
            <content:encoded><![CDATA[<p>There aren’t any major UI template libraries ready for plug and play in Angular 2 yet. <a href="https://github.com/angular/material2">Angular 2 Material Design</a> is in alpha. The <a href="https://github.com/ng-bootstrap/ng-bootstrap">Bootstrap library for Angular 2 is also in development on Github</a>, but not ready for prime time. This means that we’re left largely to our own devices to build the UI for our Angular 2 projects.</p><p>Let’s take a look at how we can get our Angular 2 project going using Bootstrap, but only the stylesheets — no bootstrap.js or jQuery. We’ll use Bootstrap 3, the current stable release, rather than Bootstrap 4 that the <br>Angular 2 Bootstrap project is targeting.</p><p>In this article, we’ll build a Bootstrap navbar as an Angular 2 component and enable its mobile view toggle functionality through the component class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qyv3ekU6BIQ7zwImny73kA.gif" /></figure><p>We’ll take the path of least resistance and simply get the menu to show and hide. For this tutorial, we’ll forgo the transition animation.</p><p>To get started, create the NavbarComponent. I put mine in the <em>CoreModule </em>of my Angular 2 application. To learn more about the module architecture I use, read <a href="https://medium.com/@ct7/angular2-module-architecture-and-example-seed-project-35b7410264f5#.4nq3rn6m9">this article</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*mZ_os5PkODy7yKTj4H3jTg.png" /></figure><p>We start with a bare bones Bootstrap navbar. The .collapse css classes are not added to the html yet.</p><pre>&lt;!-- core/navbar.component.html --&gt;<br>&lt;nav class=&quot;navbar navbar-inverse navbar-fixed-top&quot;&gt;<br>    &lt;div class=&quot;container-fluid&quot;&gt;<br>        &lt;div class=&quot;navbar-header&quot;&gt;<br>            &lt;a class=&quot;navbar-brand&quot;&gt;Project Manager&lt;/a&gt;<br>        &lt;/div&gt;<br>        &lt;ul class=&quot;nav navbar-nav&quot;&gt;<br>            &lt;li&gt;&lt;a&gt;Link 1&lt;/a&gt;&lt;/li&gt;<br>            &lt;li&gt;&lt;a&gt;Link 2&lt;/a&gt;&lt;/li&gt;<br>        &lt;/ul&gt;<br>    &lt;/div&gt;<br>&lt;/nav&gt;</pre><p>The TypeScript file contains the following.</p><pre>// core/navbar.component.ts<br>import { Component } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;</pre><pre><a href="http://twitter.com/Component">@Component</a>({<br>    selector: &#39;ct-navbar&#39;,<br>    templateUrl: &#39;app/core/navbar.component.html&#39;<br>})<br>export class NavbarComponent { }</pre><p>Add the navbar to the in the AppComponent template.</p><pre>&lt;!-- /app.component.html --&gt;<br>&lt;!-- navbar --&gt;<br><strong>&lt;ct-navbar&gt;&lt;/ct-navbar&gt;</strong><br>&lt;!-- feature content --&gt;<br>&lt;ct-project-center&gt;&lt;/ct-project-center&gt;</pre><p>Run the app and the navbar will render as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*42XnV2vMgDxdHzm6TU8KcA.gif" /></figure><p>Notice that bootstrap.css handles the display of the mobile navbar for us with a media query — @media(min-width: 768px){...}</p><p>To get our navbar to collapse, we add some more markup to our template, using the <a href="http://getbootstrap.com/components/#navbar">Bootstrap documentation</a> as our guide.</p><pre>&lt;nav class=&quot;navbar navbar-inverse navbar-fixed-top&quot;&gt;<br>    &lt;div class=&quot;container-fluid&quot;&gt;<br>        &lt;div class=&quot;navbar-header&quot;&gt;<br>            <strong>&lt;button type=&quot;button&quot; class=&quot;navbar-toggle collapsed&quot;&gt;<br>                &lt;span class=&quot;sr-only&quot;&gt;Toggle navigation&lt;/span&gt;<br>                &lt;span class=&quot;icon-bar&quot;&gt;&lt;/span&gt;<br>                &lt;span class=&quot;icon-bar&quot;&gt;&lt;/span&gt;<br>                &lt;span class=&quot;icon-bar&quot;&gt;&lt;/span&gt;<br>            &lt;/button&gt; &lt;!-- #1 --&gt;</strong><br>            &lt;a class=&quot;navbar-brand&quot;&gt;Project Manager&lt;/a&gt;<br>        &lt;/div&gt;<br>         <strong>&lt;div class=&quot;collapse navbar-collapse&quot;&gt; </strong><br>            &lt;ul class=&quot;nav navbar-nav&quot;&gt;<br>                &lt;li&gt;&lt;a&gt;Link 1&lt;/a&gt;&lt;/li&gt;<br>                &lt;li&gt;&lt;a&gt;Link 2&lt;/a&gt;&lt;/li&gt;<br>            &lt;/ul&gt;<br>        <strong>&lt;/div&gt; &lt;!-- #2 --&gt;</strong><br>    &lt;/div&gt;<br>&lt;/nav&gt;</pre><ol><li>Add the &lt;button&gt; with the <em>navbar-toggle</em> and <em>collapsed </em>classes. It is shown when the browser viewport width is less than 768px.</li><li>Wrap the &lt;ul&gt; element in a &lt;div&gt; with the <em>collapse </em>and <em>navbar-collapse </em>classes. This will cause the controls in the &lt;ul&gt; list to no longer be displayed on the mobile view.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*fDVc3M5TnMxzOruhlfu37g.png" /></figure><p>Try adding the <em>in </em>class to the &lt;div&gt;.</p><pre>&lt;div class=&quot;collapse navbar-collapse <strong>in</strong>&quot;&gt;</pre><p>You’ll see that adding this class is the mechanism for expanding the menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*PsQ5dz9Q4IPc7FQgjoIMvg.png" /></figure><p>To get the menu to work, we need Angular to toggle this class for us.</p><h4>NgClass</h4><p>Angular provides the <a href="https://angular.io/docs/ts/latest/api/common/index/NgClass-directive.html">NgClass directive</a> as a means to add and remove classes from html elements. It accepts three different types of input as an argument:</p><ul><li><em>string — </em>Input a string to ngClass to add one or more classes. Multiple classes are separated by a space. e.g. [ngClass]=&quot;&#39;first second&#39;&quot;</li><li><em>Array — </em>Input an array containing the string values of the classes you want to add.</li><li><em>Object — </em>Input an object where the object property represents the class. The property is set to a boolean indicating whether or not the class should be added to the the html element.</li></ul><p>NgClass is part of the <em>CommonModule, </em>which most likely has already been imported into the module you are working on.</p><p>We’ll apply the NgClass directive to our template, inputting an object as an argument.</p><pre>&lt;!-- core/navbar.component.html --&gt;<br>...<br>&lt;div class=&quot;collapse navbar-collapse&quot;<br>     <strong>[ngClass]=&quot;{ &#39;in&#39;: true }</strong>&quot;&gt;<br>     &lt;ul class=&quot;nav navbar-nav&quot;&gt;<br>           &lt;li&gt;&lt;a&gt;Link 1&lt;/a&gt;&lt;/li&gt;<br>           &lt;li&gt;&lt;a&gt;Link 2&lt;/a&gt;&lt;/li&gt;<br>     &lt;/ul&gt;<br>&lt;/div&gt;<br>...</pre><p>We hard coded in the value <em>true </em>just to get a handle on the syntax and verify it works. Run the app and verify that the navbar is open at the mobile <br>screen size.</p><p>In the component class, let’s create a variable to store the state of the navbar and create a method to use as the click handler.</p><pre>// core/navbar.component.ts<br>...<br>export class NavbarComponent {<br>    <strong>isIn = false;   // store state<br>    toggleState() { // click handler<br>        let bool = this.isIn;<br>        this.isIn = bool === false ? true : false; <br>    }</strong><br>}</pre><p>Now we make use of these component properties in our template.</p><pre>&lt;!-- core/navbar.component.html --&gt;<br>&lt;nav class=&quot;navbar navbar-inverse navbar-fixed-top&quot;&gt;<br>    &lt;div class=&quot;container-fluid&quot;&gt;<br>        &lt;div class=&quot;navbar-header&quot;&gt;<br>                &lt;button type=&quot;button&quot; <br>                        class=&quot;navbar-toggle collapsed&quot;<br>                        <strong>(click)=&quot;toggleState()&quot;</strong>&gt;<br>                &lt;span class=&quot;sr-only&quot;&gt;Toggle navigation&lt;/span&gt;<br>                &lt;span class=&quot;icon-bar&quot;&gt;&lt;/span&gt;<br>                &lt;span class=&quot;icon-bar&quot;&gt;&lt;/span&gt;<br>                &lt;span class=&quot;icon-bar&quot;&gt;&lt;/span&gt;<br>            &lt;/button&gt;<br>            &lt;a class=&quot;navbar-brand&quot;&gt;Project Manager&lt;/a&gt;<br>        &lt;/div&gt;<br>         &lt;div class=&quot;collapse navbar-collapse&quot;<br>              [ngClass]=&quot;{ &#39;in&#39;: <strong>isIn </strong>}&quot;&gt;<br>            &lt;ul class=&quot;nav navbar-nav&quot;&gt;<br>                &lt;li&gt;&lt;a&gt;Link 1&lt;/a&gt;&lt;/li&gt;<br>                &lt;li&gt;&lt;a&gt;Link 2&lt;/a&gt;&lt;/li&gt;<br>            &lt;/ul&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/nav&gt;</pre><p>That’s it. We now have a functional navbar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*EQC3jfXHYZ7HSb2s0JT_OQ.gif" /></figure><p>This same method can be applied to make use of many Bootstrap components in your Angular 2 project, including drop-down menus and accordion-style collapsible panels.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6b3f67b037b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stay determined, no matter the circumstances. Find the heroes that inspire you to soldier on.]]></title>
            <link>https://medium.com/@ct7/stay-determined-no-matter-the-circumstances-find-the-heroes-that-inspire-you-to-soldier-on-b5663a8b2861?source=rss-168b2940d972------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5663a8b2861</guid>
            <category><![CDATA[space]]></category>
            <category><![CDATA[management]]></category>
            <category><![CDATA[entrepreneurship]]></category>
            <category><![CDATA[nasa]]></category>
            <category><![CDATA[leadership]]></category>
            <dc:creator><![CDATA[Thomas Rundle]]></dc:creator>
            <pubDate>Fri, 11 Nov 2016 20:33:46 GMT</pubDate>
            <atom:updated>2016-11-11T20:54:02.541Z</atom:updated>
            <content:encoded><![CDATA[<p>Today, I turn to America’s nascent space program in the 1960s for my heroes. A literal Moon shot happened in an America that was just as divided and plagued by bureaucratic waste as it is today. John F. Kennedy’s speeches, often seen as unifying, were the most memorable ever made by any politician on space policy. It’s easy to forget that in the 10 years from NASA’s founding to the lunar landing of Apollo 11 there were four very different presidents.</p><p>NASA was formed during Dwight D. Eisenhower’s administration in 1958. In 1969, Richard Nixon presided in the Oval Office as Neil Armstrong took the first steps on the Moon. Against a backdrop of civil unrest and uncertainty, stirred by the Vietnam War, Civil Rights Movement, and the Cold War, thousands of men and women, working for NASA and the agency’s subcontractors, spent long hours and endured harsh setbacks, ultimately achieving something that had appeared impossible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MCFC4Cd6sv81nFe31Mhwvw.jpeg" /><figcaption>Buzz Aldrin during Apollo 11</figcaption></figure><p>The men and women of America’s space program saw the Soviet Union appear to pull ahead in technological capability, setting early records in space. Things looked grim. Soviet Premier Nikita Khrushchev had famously told the West —<strong> “We will bury you!”</strong>. Later, they witnessed the assassination of John F. Kennedy in 1963, and then the assassinations of Martin Luther King, Jr and Robert F. Kennedy in 1968.</p><p>Early NASA rocket launches failed publicly and spectacularly. In his memoir, Gene Kranz, famous for serving as Flight Director for both Apollo 11 and Apollo 13, described the first unmanned Project Mercury launch as the “four-inch flight”. When the clock struck zero at the televised launch, a great cloud of smoke erupted from the launch pad. Something appeared to blast off into sky at a startling rate; however, when the smoke cleared, the rocket remained on the ground. Then, parachutes deployed from the nose of the capsule. Only the escape tower had launched.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t7cVI6gs1NIQ0_p-nsQ8fQ.jpeg" /><figcaption>Mercury-Redstone 1 launch failure. Escape tower is located on the tip of the capsule.</figcaption></figure><blockquote>“All hell broke loose. The Redstone had lifted a few inches off the launch pad and then the engine shut down. By some miracle, the rocket had landed back on the launcher cradle.</blockquote><blockquote>When the escape tower cut loose, unguided and spewing flame, it corkscrewed to an altitude of about 4,000 feet. As it plummeted back to Earth, loudspeakers around the facility blared out warnings to the astronauts, engineers, and VIPs in the viewing area to take cover.”</blockquote><blockquote>— Gene Kranz, Failure Is Not An Option</blockquote><p>The rocket was still live, and the engineers had no way to shut it down, because the umbilical cables connecting the rocket to launch control had disconnected. Mission control and the launch team feared that the parachutes would catch wind, toppling the rocket. Still fully pressurized for launch, the rocket could explode killing everyone nearby. Kranz describes the reaction of Christopher Kraft, NASA’s first Flight Director, as he listened to the team scrambling to come up with a solution.</p><blockquote>“After impatiently listening to a pretty far-out proposal to depressurize the rocket by using a rifle to shoot holes in the fuel and oxidizer tanks, Kraft sputtered and growled, ‘Dammit, that’s no way to do it! They sound like a bunch that just started spring training!’”</blockquote><blockquote>— Gene Kranz, Failure Is Not An Option</blockquote><p>Kranz says they ultimately went with a plan proposed by one of the test conductors that called for waiting until the next morning before doing anything, since weather forecasts predicted the wind to remain calm. By the following morning, batteries would be depleted and valves would open, depressurizing the rocket, making it safe to approach. The plan worked, they salvaged the capsule and rocket, and they moved forward.</p><p>Six months later, they would launch their first successful manned flight, putting Alan Shepard into space. Another year after that, John Glenn would be the first American to enter Earth’s orbit. In another seven years, they would beat the Soviets to the Moon.</p><p>When I was pursuing my undergraduate degree, my heroes were outspoken rebels. I loved them because they defied societal norms and vehemently criticized the system. My heroes had extraordinary eloquence, and their body of work was made more impressive because their self-destructive excesses hadn’t prevented them from producing that work. Hunter S. Thompson placed foremost in this group at this time in my life.</p><p>Now I need heroes who believed in the system and society, despite its many flaws, and kept going, undeterred by valid causes for cynicism, moving forward to great accomplishment. I need this same faith to stay relentless in my career pursuits— to maintain confidence that the time and energy I invest in my work is worth it despite ambiguous circumstances and hard to predict outcomes. I must learn from investments that fail, rather than be discouraged or allocate blame. Maintaining this resilience has been harder than any specific technical challenge.</p><p>It’s always easy to find a reason to not do something, not put forth your best effort, or give up, especially when you are focused on what is wrong with everything around you rather than what is right. In his novel, <em>Anathem, </em>Neal Stephenson says it better, writing these words as spoken by one of the novel’s characters:</p><blockquote>“Nothing is more important than that you see and love the beauty that is right in front of you, or else you will have no defense against the ugliness that will hem you in and come at you in so many ways.”</blockquote><blockquote>— Neal Stephenson, Anathem</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5663a8b2861" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a reusable table layout for your Angular 2 project]]></title>
            <link>https://medium.com/@ct7/building-a-reusable-table-layout-for-your-angular-2-project-adf6bba3b498?source=rss-168b2940d972------2</link>
            <guid isPermaLink="false">https://medium.com/p/adf6bba3b498</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Thomas Rundle]]></dc:creator>
            <pubDate>Thu, 10 Nov 2016 20:14:44 GMT</pubDate>
            <atom:updated>2016-11-10T20:14:44.553Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the most exciting things about working with Angular 2 is how quickly you can build up your application with components. Building components isn’t very hard, but creating highly-reusable, general-purpose components requires some planning.</p><p>This article demonstrates how to build a versatile table layout component. Because such a component is a must have for any application that displays data, it’s a good choice as an example.</p><p>The completed component will dynamically generate html tables like the ones shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z2FwKMwpck6SIlsmhb8g9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LM252vw0QLrOae9SE8E3MA.png" /></figure><p>In the finished example, the html selectors used to generate these tables, respectively, are:</p><pre>&lt;ct-table [records]=&quot;projects&quot; <br>          [caption]=&quot;&#39;NASA Projects&#39;&quot; <br>          [settings]=&quot;projectSettings&quot;&gt;<br>&lt;/ct-table&gt;<br>&lt;ct-table [records]=&quot;people&quot;<br>          [caption]=&quot;&#39;NASA Astronauts&#39;&quot;<br>          [settings]=&quot;personnelSettings&quot;&gt;<br>&lt;/ct-table&gt;</pre><p>You’ll find that the simply attaching an *ngFor on the &lt;tr&gt; and &lt;td&gt; does not handle many use cases.</p><pre>&lt;tr *ngFor=&quot;let record of records&quot;&gt;<br>    &lt;td *ngFor=&quot;let key of objectKeys&quot;&gt;<br>        {{ record[key] }}<br>    &lt;/td&gt;<br>&lt;/tr&gt;</pre><p>You need to be able to format table cells based on the value they contain and define column headings that aren’t left up to chance based on the properties of the data fetched by your data service.</p><h4>Requirements</h4><p>With this in mind, the following requirements have been defined for a general-purpose table component.</p><ul><li>Control the name of the column headers and the ordering of columns based on settings supplied by a parent component.</li><li>Format cell values differently based on the type of value the cell contains. Design based on what an Excel user would expect. For example, numerical values are aligned right, whereas text values are aligned left.</li><li>Handle nested arrays and objects contained by the record. For example, in a record such as:</li></ul><pre>{<br>  name: &#39;Tom&#39;,<br>  interests: [&#39;writing&#39;, &#39;programming&#39;, &#39;playing drums&#39;],<br>  emergency_contacts: [<br>    { <br>       name: &#39;Kathy&#39;,<br>       mobile: &#39;832-867-5309&#39;<br>    }...<br>  ]<br>}</pre><ul><li>Find the appropriate column value when supplied objects have different property keys used to access that value. E.g. My <strong><em>Cost </em></strong>column value could be stored as <em>object.cost</em>, <em>object.total_cost, </em>or <em>object.funding</em>.</li><li>Explicitly indicate when column value is undefined rather than display an empty cell.</li></ul><h4>Solution design</h4><p>To meet these requirements, we will build the following elements:</p><ul><li><strong>TableLayoutComponent</strong>: Iterates through records and record properties to create the table. Required input is an array of records. Also accepts inputs for table <em>caption </em>and for <em>settings</em> used to configure the table format and style.</li></ul><pre>// usage<br>&lt;ct-table [records]=&quot;projects&quot; <br>          [caption]=&quot;&#39;NASA Projects&#39;&quot; <br>          [settings]=&quot;columnSettings&quot;&gt;<br>&lt;/ct-table&gt;</pre><ul><li><strong>FormatCellPipe</strong>: Transforms cell values based on the type of value returned by the object property. Handles arrays and objects nested in the record object.</li><li><strong>StyleCellDirective</strong>: Applies styling to the table cell based on the type of value contained by the cell.</li><li><strong>ColumnMap class</strong>: Constructs configuration settings for each column. Supplies the appropriate parameters to the TableLayoutComponent, FormatCellPipe, and StyleCellDirective for each column. Constructs class instances initialized with default values, if user settings are not supplied.</li></ul><p>Completed template based on above requirements:</p><pre>&lt;tr *ngFor=&quot;let record of records&quot;&gt;<br>  &lt;td *ngFor=&quot;<strong>let map of columnMaps</strong>&quot; // map: instance of  ColumnMap<br>     <strong>[ctStyleCell]=&quot;record[map.access(record)</strong>]&quot; //StyleCellDirective<br>   &gt;<br>     {{ record[<strong>map.access(record)</strong>] <strong>| formatCell:map.format</strong> }}<br>        // record access key identified by ColumnMap instance<br>        // resulting value sent to FormatCellPipe for text format<br>  &lt;/td&gt;<br>&lt;/tr&gt;</pre><h3>Set up the baseline application</h3><p>Unfortunately, it can take a lot of work just to establish a baseline app with a common structure. If you want to follow this demonstration using the same code base, you can <a href="https://github.com/conduitl/ng-savant/tree/master/seed">download this seed project</a> from Github. The structure of this seed project is <a href="https://medium.com/@ct7/angular2-module-architecture-and-example-seed-project-35b7410264f5#.q5sf2f5lf">described in this article</a>.</p><p>If you use the same setup as the seed project, the app directory will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*nU4wgGD0zh66Y4g3OxIr5Q.png" /></figure><p>We will build our solution in the <em>shared </em>folder. This folder contains the <em>SharedModule </em>that exports components we plan to reuse in various feature modules in our application. This aligns with the architecture recommendations in the <a href="https://angular.io/docs/ts/latest/guide/ngmodule.html">Angular Docs on NgModule</a>.</p><p>The <em>SharedModule </em>will be the core deliverable of this demonstration. However, the only way we will know if the <em>SharedModule </em>meets our requirements is if we test it with a feature module that imports and implements it.</p><p>Therefore, we need to create a feature module, called <em>ProjectCenterModule, </em>that will implement the <em>TableLayoutComponent</em> developed in the <em>SharedModule</em>.</p><h4>Setup the feature module</h4><p>The initial <em>ProjectCenterModule </em>has the following directory structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*ntYuK90pzQenxjivVWQ62Q.png" /></figure><p>The following is the data we’ll initially display in our table.</p><pre>// ./project-center/fakedata.ts<br>import { Project, Person } from &#39;./model&#39;;<br>export const PROJECTS: Project[] = [<br>    {<br>        id: 1,<br>        name: &#39;Mercury&#39;,<br>        cost: 277000000,<br>        first_flight: &#39;September 9, 1959&#39;,<br>        status: &#39;Complete&#39;<br>    },<br>    {<br>        id: 2,<br>        name: &#39;Gemini&#39;,<br>        cost: 1300000000,<br>        first_flight: &#39;April 8, 1964&#39;,<br>        status: &#39;Complete&#39;<br>    },<br>    {<br>        id: 3,<br>        name: &#39;Apollo&#39;,<br>        cost: 25400000000,<br>        first_flight: &#39;February 26, 1966&#39;,<br>        status: &#39;Complete&#39;<br>    },<br>    {<br>        id: 4,<br>        name: &#39;Skylab&#39;,<br>        launch: &#39;May 14, 1973&#39;,<br>        status: &#39;Complete&#39;<br>    },<br>    {<br>        id: 5,<br>        name: &#39;Apollo-Soyuz&#39;,<br>        launch: &#39;July 15, 1975&#39;,<br>        status: &#39;Complete&#39;<br>    },<br>    {<br>        id: 6,<br>        name: &#39;Space Shuttle&#39;,<br>        total_cost: 196000000000,<br>        first_flight: &#39;August 12, 1977&#39;,<br>        status: &#39;Complete&#39;<br>    }<br>    <br>];<br>export const PERSONNEL: Person[] = [<br>    { <br>        id: 151, <br>        name: &#39;Alan B. Shepard, Jr.&#39;, <br>        job: &#39;Astronaut&#39;, <br>        year_joined: 1959,<br>        missions: [&#39;MR-3&#39;, &#39;Apollo 14&#39;]<br>    },<br>    { <br>        id: 152, <br>        name: &#39;Virgil I. Grissom&#39;, <br>        job: &#39;Astronaut&#39;, <br>        year_joined: 1959,<br>        missions: [&#39;MR-4&#39;, &#39;Apollo 1&#39;]<br>    },<br>    { <br>        id: 153, <br>        name: &#39;John H. Glenn, Jr.&#39;, <br>        job: &#39;Astronaut&#39;, <br>        year_joined: 1959,<br>        missions: [&#39;MA-6&#39;,&#39;STS-95&#39;]<br>    },<br>    { <br>        id: 154, <br>        name: &#39;M. Scott Carpenter&#39;, <br>        job: &#39;Astronaut&#39;, <br>        year_joined: 1959,<br>        missions: [&#39;MA-7&#39;]<br>    }<br>];</pre><p>And below are the model classes for that data.</p><pre>// ./project-center/model.ts<br>export class Project { <br>    id: number;<br>    name: string;<br>    cost?: number;<br>    total_cost?: number;<br>    first_flight?: string;<br>    launch?: string;<br>    status: string;<br>}<br>export class Person {<br>    id: number;<br>    name: string;<br>    year_joined: number;<br>    job: string;<br>    missions: string[];<br>    crewWith?: { <br>        id: number,<br>        name: string<br>    }[];<br>    manager?: any;<br>}</pre><p>The module file includes one component and one service. It imports the <em>SharedModule </em>that handles all the hard work of actually building the tables for the various views in our application.</p><pre>// ./project-center/project-center.module.ts</pre><pre>import { NgModule } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;</pre><pre>import { SharedModule } from &#39;../shared/shared.module&#39;;</pre><pre>import { ProjectCenterComponent } from &#39;./project-center.component&#39;;<br>import { ProjectService } from &#39;./project.service&#39;;</pre><pre><a href="http://twitter.com/NgModule">@NgModule</a>({<br>    imports: [ SharedModule ],<br>    declarations: [ ProjectCenterComponent ],<br>    providers: [ ProjectService ],<br>    exports: [ ProjectCenterComponent ]<br>})<br>export class ProjectCenterModule { }</pre><p>The service imports our mock data with get methods that simply return the imported data. In a real data service, methods would use Promise or Observable interfaces for asynchronous request/response handling.</p><pre>// ./project-center/project.service.ts<br>import { Injectable } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;<br>import { Project, Person } from &#39;./model&#39;;<br>import { PROJECTS, PERSONNEL } from &#39;./fakedata&#39;;<br><a href="http://twitter.com/Injectable">@Injectable</a>()<br>export class ProjectService {<br>    getProjects(): Project[] {<br>        // actual implementation would use async method<br>        return PROJECTS;<br>    }<br>    getPersonnel(): Person[] {<br>        return PERSONNEL;<br>    }<br>}</pre><p>The <em>ProjectComponentComponent </em>below injects the service through the class’ constructor. The console.logs are included simply to verify the initial setup is working. We’ll perform this check shortly.</p><pre>// ./project-center/project-center.component.ts</pre><pre>import { Component, OnInit } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;<br>import { ProjectService } from &#39;./project.service&#39;;<br>import { Project, Person } from &#39;./model&#39;;<br><a href="http://twitter.com/Component">@Component</a>({<br>    selector: &#39;ct-project-center&#39;,<br>    templateUrl: &#39;app/project-center/project-center.component.html&#39;<br>})<br>export class ProjectCenterComponent implements OnInit {<br>    title: string = &#39;Project Center&#39;;<br>    projects: Project[];<br>    people: Person[];<br>    constructor(private projectService: ProjectService){}<br>    ngOnInit() {<br>        this.projects = this.projectService.getProjects();<br>        this.people =   this.projectService.getPersonnel();<br>        console.log(this.projects);<br>        console.log(this.people);<br>    }<br> }</pre><p>The initial template is minimalist. There’s not even a table yet. Note that <a href="http://getbootstrap.com/">Bootstrap </a>is used for styling.</p><pre>// ./project-center/project-center.component.html<br>&lt;div class=&quot;container-fluid&quot;&gt;<br>    &lt;div class=&quot;page-header&quot;&gt;<br>        &lt;h1&gt;{{ title }}&lt;/h1&gt;<br>    &lt;/div&gt;<br>&lt;/div&gt;</pre><h4>Setup SharedModule</h4><p>The <em>SharedModule </em>contains the table component we’ll be working on.</p><pre>// ./shared/shared.module.ts</pre><pre>import { NgModule } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;<br>import { CommonModule } from &#39;<a href="http://twitter.com/angular/common">@angular/common</a>&#39;;</pre><pre>import { TableLayoutComponent } from &#39;./table-layout.component&#39;;</pre><pre><a href="http://twitter.com/NgModule">@NgModule</a>({<br>    imports: [ CommonModule ],<br>    declarations: [ TableLayoutComponent ],<br>    exports: [<br>        CommonModule, <br>        TableLayoutComponent <br>    ]<br>})<br>export class SharedModule { }</pre><p>The component itself does not do anything yet.</p><pre>// ./shared/table-layout.component.ts</pre><pre>import { Component } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;</pre><pre><a href="http://twitter.com/Component">@Component</a>({<br>    selector: &#39;ct-table&#39;,<br>    templateUrl: &#39;app/shared/table-layout.component.html&#39;<br>})<br>export class TableLayoutComponent { }</pre><p>And the initial template is just a static table.</p><pre>// ./shared/table-layout.component.html</pre><pre>&lt;table class=&quot;table&quot;&gt;<br>    &lt;caption&gt;Table&lt;/caption&gt;<br>    &lt;thead&gt;<br>        &lt;tr&gt;<br>            &lt;th&gt;Column 1&lt;/th&gt;<br>            &lt;th&gt;Column 2&lt;/th&gt;<br>        &lt;/tr&gt;<br>    &lt;/thead&gt;<br>    &lt;tbody&gt;<br>        &lt;tr&gt;<br>            &lt;td&gt;Some <em>value</em>&lt;/td&gt;<br>            &lt;td&gt;Some value&lt;/td&gt;<br>        &lt;/tr&gt;<br>    &lt;/tbody&gt;<br>&lt;/table&gt;</pre><p>If you like to see how the root AppModule and AppComponent are setup, please read <a href="https://medium.com/@ct7/angular2-module-architecture-and-example-seed-project-35b7410264f5#.uydohymwz">this article describing the seed project setup</a>.</p><p>Test out the initial version of <em>ProjectCenterModule </em>and <em>SharedModule </em>by running the app with them loaded into your AppModule and the <br><strong>&lt;ct-project-center&gt;</strong> selector inserted into your AppComponent template.</p><p>The page will be empty except for the <em>Project Center </em>title. Check the console in developer tools. Verify that you see the arrays stored in the <em>projects </em>and <em>people </em>variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*HhXHmUc4cPsmOO713i1rMw.png" /></figure><p>Now add the <strong>&lt;ct-table&gt; </strong>selector to the <em>ProjectCenterComponent </em>template.</p><pre>// ./project-center/project-center.component.html<br>&lt;div class=&quot;container-fluid&quot;&gt;<br>    &lt;div class=&quot;page-header&quot;&gt;<br>        &lt;h1&gt;{{ title }}&lt;/h1&gt;<br>    &lt;/div&gt;<br>    <strong>&lt;ct-table&gt;&lt;/ct-table&gt;</strong><br>&lt;/div&gt;</pre><p>Refresh the app. Now you should see the static table as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*Fxxy14QzOIFWSFjAkCDLxg.png" /></figure><p>After verifying the setup, we are ready to start building our solution.</p><h3>Develop the table layout</h3><h4>First draft of TableLayoutComponent</h4><p>We are ready to build our first iteration of <em>TableLayoutComponent </em>that dynamically generates the table based on supplied data.</p><p>We do the following:</p><ol><li>Define <strong><em>Inputs </em></strong>each table instance will receive.</li><li>Capture object keys from data to determine table columns. Make sure keys are updated whenever <strong><em>Input</em></strong><em> </em>data changes.</li><li>Iterate through objects and object keys in the component template.</li></ol><pre>// ./shared/table-layout.component.ts<br>import { Component, <strong>Input, OnChanges</strong> } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;<br><a href="http://twitter.com/Component">@Component</a>({<br>    selector: &#39;ct-table&#39;,<br>    templateUrl: &#39;app/shared/table-layout.component.html&#39;<br>})<br>export class TableLayoutComponent <strong>implements OnChanges</strong> { <br>    <a href="http://twitter.com/Input"><strong>@Input</strong></a><strong>() records: any[];<br>    </strong><a href="http://twitter.com/Input"><strong>@Input</strong></a><strong>() caption: string;<br>    keys: string[];</strong></pre><pre><strong>    ngOnChanges() {<br>        this.keys = Object.keys(this.records[0]);<br>    }</strong><br>}</pre><p>In the controller class of <em>TableLayoutComponent</em>, we implement <em>OnChanges. </em>We use the associated method <em>ngOnChanges() </em>to grab the keys from the first record each time a Angular detects a change in <em>Input() </em>from the parent component.</p><p>Of course, retrieving the keys this way means that we are relying on a uniform array of objects with no uninitialized optional properties.</p><p>The template can now iterate through the input records and the retrieved keys to generate the table.</p><pre>// ./shared/table-layout.component.ts</pre><pre>&lt;table class=&quot;table&quot;&gt;<br>    <strong>&lt;caption *ngIf=&quot;caption&quot;&gt;{{ caption }}&lt;/caption&gt;</strong><br>    &lt;thead&gt;<br>        &lt;tr&gt;<br>            <strong>&lt;th *ngFor=&quot;let key of keys&quot;&gt;{{ key }}&lt;/th&gt;</strong><br>        &lt;/tr&gt;<br>    &lt;/thead&gt;<br>    &lt;tbody&gt;<br>        <strong>&lt;tr *ngFor=&quot;let record of records&quot;&gt;<br>            &lt;td *ngFor=&quot;let key of keys&quot;&gt;{{ record[key] }}&lt;/td&gt;<br>        &lt;/tr&gt;</strong><br>    &lt;/tbody&gt;<br>&lt;/table&gt;</pre><p>We attach an *ngIf to the &lt;caption&gt;. We want this input to be optional. If no caption is defined, the caption will not be attached to the table.</p><p>For the column header, we iterate through the keys.</p><p>For the table body, we iterate through the records and then nest another *ngFor on the &lt;td&gt; to iterate through the keys.</p><p>Before we can test our table. We have to use it in the <em>ProjectCenterComponent </em>template inside our feature module.</p><pre>&lt;div class=&quot;container-fluid&quot;&gt;<br>    &lt;div class=&quot;page-header&quot;&gt;<br>        &lt;h1&gt;{{ title }}&lt;/h1&gt;<br>    &lt;/div&gt;<br>    <strong>&lt;ct-table [records]=&quot;projects&quot;<br>              [caption]=&quot;&#39;NASA Projects&#39;&quot;&gt;<br>    &lt;/ct-table&gt;<br>    &lt;ct-table [records]=&quot;people&quot;<br>              [caption]=&quot;&#39;NASA Astronauts&#39;&quot;&gt;<br>    &lt;/ct-table&gt;</strong><br>&lt;/div&gt;</pre><p>Run the application. It’s a good start, but it has the limitations we’d expect. Our headers are ugly and the large numbers in the cost column are hard to read without currency formatting.</p><p>We have dates in our data for <strong>Skylab </strong>and <strong>Apollo-Soyuz</strong> but they are accessed through the property key <em>“launch” </em>rather than <em>“first_flight”</em>. The records are setup this way because there was only one launch for each rather than several such as in the <em>Apollo </em>program.</p><p>In the astronauts list, we see that Angular template expressions actually handle the arrays nested in the <em>“missions” </em>property rather well. However, we’d still like to see a space between each array element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*q9LfH8JMmMZFGvKrSZLKjw.png" /></figure><h4>A model for configuration settings</h4><p>The TableLayoutComponent will only be able to fine tune how the table is displayed if the parent component provides information to it about how it want the data to be displayed.</p><p>We need to create a model for these configuration settings. Create the <em>layout.model.ts </em>file in the <em>shared </em>folder.</p><pre>// ./shared/layout.model.ts<br>export class ColumnSetting {<br>    primaryKey: string;<br>    header?: string;<br>    format?: string;<br>    alternativeKeys?: string[];<br>}</pre><p>We import this class into the component that is implementing the table layout. The <strong>primaryKey </strong>is the property on the object that we expect to contain the value for a particular table column, and <strong>header</strong> is the title we want to apply to that column. The other properties on the model will be discussed and applied later on.</p><p>We define settings for our projects table, but not our astronauts table. We want the settings to be optional. If settings are not supplied, <em>TableLayoutComponent </em>should attempt to generate a clean view of the table by applying default settings.</p><pre>// ./project-center/project-center.component.ts<br>...<br><strong>import { ColumnSetting } from &#39;../shared/layout.model&#39;;</strong><br><a href="http://twitter.com/Component">@Component</a>({...})<br>export class ProjectCenterComponent implements OnInit {<br>    ...<br>    <strong>projectSettings: ColumnSetting[] = <br>      [<br>          {<br>              primaryKey: &#39;name&#39;,<br>              header: &#39;Name&#39;<br>          },<br>          {<br>              primaryKey: &#39;first_flight&#39;,<br>              header: &#39;First launch&#39;<br>          },<br>          {<br>              primaryKey: &#39;cost&#39;,<br>              header: &#39;Cost&#39;<br>          }<br>      ];</strong><br>    constructor(private projectService: ProjectService){}<br>    ngOnInit() {...}<br> }</pre><p>The settings below will generate a three column table. Columns are generated only if a settings object with the <strong>primaryKey </strong>property is defined. They define the appropriate header format for each column and the columns are generated in the same order as the array. In this way, we control which values are displayed from each record and the order in which they are displayed.</p><p>In the <em>ProjectCenterComponent </em>template, we bind the <strong><em>projectSettings </em></strong>to the <strong>settings </strong>input property that we will soon define in our <em>TableLayoutComponent</em>.</p><pre>// ./project-center/project-center.component.html<br>...<br>&lt;ct-table [records]=&quot;projects&quot;<br>          [caption]=&quot;&#39;NASA Projects&#39;&quot;<br>          <strong>[settings]=&quot;projectSettings&quot;</strong>&gt;<br>&lt;/ct-table&gt;<br>...</pre><p>Back in the <em>shared </em>folder, we modify <em>TableLayoutComponent</em>. We import the <em>ColumnSetting </em>class and apply it in the <em>ngOnChanges() </em>method. We call the property containing an array of <em>ColumnSetting </em>instances <em>columnMaps. </em>We think of each <em>ColumnSetting </em>instance as having a map that tells us where to get all the information we need for a particular column, hence the naming convention.</p><pre>// ./shared/table-layout.component.ts<br>import { Component, Input, OnChanges } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;<br><strong>import { ColumnSetting } from &#39;./layout.model&#39;;</strong><br><a href="http://twitter.com/Component">@Component</a>({...})<br>export class TableLayoutComponent implements OnChanges { <br>    <a href="http://twitter.com/Input">@Input</a>() records: any[];<br>    <a href="http://twitter.com/Input">@Input</a>() caption: string;<br>    <a href="http://twitter.com/Input"><strong>@Input</strong></a><strong>() settings: ColumnSetting[];</strong><br>    <strong>columnMaps: ColumnSetting[]; </strong><br>    ngOnChanges() {<br>        <strong>if (this.settings) { </strong>// when settings provided<strong><br>            this.columnMaps = this.settings;<br>        } else { </strong>// no settings, create column maps with defaults<strong><br>            this.columnMaps = Object.keys(this.records[0])<br>                .map( key =&gt; {<br>                     return {<br>                         primaryKey: key,<br>                         header: key.slice(0, 1).toUpperCase() + <br>                            key.replace(/_/g, &#39; &#39; ).slice(1)<br>                }<br>            });<br>        }</strong><br>    }<br>}</pre><p>Right now setting objects are equivalent to the column maps. Therefore, if settings are provided, we can simply initialize the <em>columnMaps </em>component property to the <em>settings</em> input.</p><p>If the component isn’t provided with settings, we do our best by once again grabbing the keys from the first record. We map over these keys, returning objects with the same structure as <em>ColumnSetting. </em>We clean up the column headers by capitalizing the first letter and replacing underscores with spaces.</p><p>We update the template to make use of the <em>columnMaps </em>component property<em>.</em></p><pre>&lt;!-- ./shared/table-layout.component.html --&gt;<br>&lt;table class=&quot;table&quot;&gt;<br>    &lt;caption *ngIf=&quot;caption&quot;&gt;{{ caption }}&lt;/caption&gt;<br>    &lt;thead&gt;<br>        &lt;tr&gt;<br>            &lt;th *ngFor=&quot;<strong>let map of columnMaps</strong>&quot;&gt;{{ <strong>map.header</strong> }}&lt;/th&gt;<br>        &lt;/tr&gt;<br>    &lt;/thead&gt;<br>    &lt;tbody&gt;<br>        &lt;tr *ngFor=&quot;let record of records&quot;&gt;<br>            &lt;td *ngFor=&quot;<strong>let map of columnMaps</strong>&quot;&gt;<br>                {{ record[<strong>map.primaryKey</strong>] }}&lt;/td&gt;<br>        &lt;/tr&gt;<br>    &lt;/tbody&gt;<br>&lt;/table&gt;</pre><p>When we run the app again, we see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rX-lsOjsM5xecC_nGZEE_g.png" /></figure><p>This is notable progress. In the projects table, we were able to control which columns are displayed and the column ordering. The astronauts table looks pretty good, despite no supplied settings.</p><p>The formatting of the cost column is still a glaring issue. Also, when no property values are found, we would like the cell to display “Not available”. This instills confidence that the app actually attempted to retrieve the value and did not encounter an error. We will tackle these requirements next by developing a pipe.</p><h4>Develop a custom pipe</h4><p>Our planned solution calls for a custom pipe call FormatCellPipe. Our short specification described it as follows.</p><blockquote><strong>FormatCellPipe</strong>: Transforms cell values based on the type of value returned by the object property. Handles arrays and objects nested in the record object.</blockquote><p>To get a quick win that demonstrates we are able to successfully define a custom pipe and use it in our application, our first iteration will just check for undefined values and return “not available” if a record property is undefined.</p><pre>// ./shared/format-cell.pipe.ts<br>import { Pipe, PipeTransform } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;<br><a href="http://twitter.com/Pipe">@Pipe</a>({ name: &#39;formatCell&#39; })<br>export class FormatCellPipe implements PipeTransform {<br>    transform(value: any) {<br>        if ( value === undefined ) {<br>            return &#39;not available&#39;;<br>        }<br>        return value;<br>    }<br>}</pre><p>Before using it, we have to declare the pipe in our <em>SharedModule.</em></p><pre>// ./shared/shared.module.ts<br>...<br><strong>import { FormatCellPipe } from &#39;./format-cell.pipe&#39;;</strong></pre><pre><a href="http://twitter.com/NgModule">@NgModule</a>({<br>    imports: [ CommonModule ],<br>    declarations: [ <br>        TableLayoutComponent,<br>        <strong>FormatCellPipe</strong><br>    ],<br>    ...</pre><p>We apply it to our table template.</p><pre>&lt;!-- ./shared/table-layout.component.html --&gt;</pre><pre>...<br>&lt;tr *ngFor=&quot;let record of records&quot;&gt;<br>     &lt;td *ngFor=&quot;let map of columnMaps&quot;&gt;<br>           {{ record[map.primaryKey] <strong>| formatCell</strong> }}<br>     &lt;/td&gt;<br>&lt;/tr&gt;<br>...</pre><p>When we run the app, we should now see the following results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H65CgCFDkxnYKRMUjYW8nw.png" /></figure><p>There are no blank cells, instead when no value is found the pipe returns “not available” to the table cell.</p><p>In the next iteration of the pipe, we handle the currency values, nested arrays, and nested objects. This version of the pipe takes an argument <em>format </em>because we will use our <em>ColumnSettings </em>objects to tell the pipe the appropriate format to use.</p><pre>// ./project-center/project-center.component.ts<br>...<br>export class ProjectCenterComponent implements OnInit {<br>    ...<br>    projectSettings: ColumnSetting[] = <br>      [<br>          ...<br>          {<br>              primaryKey: &#39;cost&#39;,<br>              header: &#39;Cost&#39;,<br>              <strong>format: &#39;currency&#39;</strong><br>          }<br>      ];<br>    ...</pre><p>If no settings are supplied, the <em>TableLayoutComponent </em>will initialize <em>ColumnSetting </em>instances with the format property set to “default”.</p><pre>// ./shared/table-layout.component.ts<br>...<br>export class TableLayoutComponent implements OnChanges { <br>    ...<br>    ngOnChanges() {<br>        if (this.settings) {<br>            this.columnMaps = this.settings; <strong>// TODO</strong><br>            <strong>// if no format provided - initialize to &#39;default&#39;      </strong><br>        } else {<br>            this.columnMaps = Object.keys(this.records[0])<br>              .map( key =&gt; {<br>                return {<br>                    primaryKey: key,<br>                    header: key.slice(0, 1).toUpperCase() + <br>                            key.replace(/_/g, &#39; &#39; ).slice(1),<br>                    <strong>format: &#39;default&#39;</strong><br>                }<br>            });<br>        }<br>    }<br>}</pre><p>We also need to handle the case where settings are supplied but those supplied settings do not specify the format. We will leave that as a to do list item for now.</p><p>We update the template to provide the format to the pipe via our column map.</p><pre>&lt;!-- ./shared/table-layout.component.html --&gt;<br>&lt;tr *ngFor=&quot;let record of records&quot;&gt;<br>     &lt;td *ngFor=&quot;let map of columnMaps&quot;&gt;<br>           {{ record[map.primaryKey] | formatCell<strong>:map.format</strong> }}<br>     &lt;/td&gt;<br>&lt;/tr&gt;</pre><p>We rewrite the FormatCellPipe to take the format argument. We leverage the Angular built-in <em>CurrencyPipe </em>for our currency values. Before use, we inject it into our pipe using dependency injection.</p><p>If the value sent to the pipe is a nested array, we join the array with a comma and a space. If the value sent to the pipe is an object, we look for a name property and return it.</p><pre>import { Pipe, PipeTransform } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;<br>import { CurrencyPipe } from &#39;<a href="http://twitter.com/angular/common">@angular/common</a>&#39;;<br><a href="http://twitter.com/Pipe">@Pipe</a>({ name: &#39;formatCell&#39; })<br>export class FormatCellPipe implements PipeTransform {<br>    constructor (<br>        private currencyPipe: CurrencyPipe<br>    ) { }<br>    transform(value: any, format: string) {<br>        if ( value === undefined ) {<br>            return &#39;not available&#39;;<br>        }</pre><pre>        if ( format === &#39;default&#39; ) {<br>            if ( Array.isArray(value) ) {<br>                if ( typeof value[0] !== &#39;object&#39; ) {<br>                    return value.join(&#39;, &#39;);<br>                } else {<br>                    return value.map( obj =&gt; {<br>                        return obj.name<br>                    }).join(&#39;, &#39;);<br>                }<br>            }<br>            if ( typeof value === &quot;object&quot;) {<br>                return value.name<br>            }<br>        }<br>        <br>        if (format === &#39;currency&#39;) {<br>            return this.currencyPipe.transform(value, &#39;USD&#39;, true);<br>        }<br>        <br>        return value;<br>    }<br>}</pre><p>Before we can run the application, we must set <em>CurrencyPipe </em>as a provider in the <em>SharedModule.</em></p><pre>// ./shared/shared.module.ts<br>...<br><strong>import { CurrencyPipe } from &#39;</strong><a href="http://twitter.com/angular/common"><strong>@angular/common</strong></a><strong>&#39;;<br>...<br></strong><a href="http://twitter.com/NgModule">@NgModule</a>({<br>    ...<br>    providers: [ <strong>CurrencyPipe </strong>]<br>})<br>export class SharedModule { }</pre><p>The pipe will later need to be expanded to handle more cases, but it’s a good starter template that meets the needs of this demonstration. Running our app, we now see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4doEHpb7nvK1lZ9NOaj2Cg.png" /></figure><p>The next step is to handle cell styling.</p><h4>Develop an attribute directive for cell styling</h4><p>Our specification is as follows.</p><blockquote><strong>StyleCellDirective</strong>: Applies styling to the table cell based on the type of value contained by the cell.</blockquote><p>And the corresponding requirement is:</p><blockquote>Format cell values differently based on the type of value the cell contains. Design based on what an Excel user would expect. For example, numerical values are aligned right, whereas text values are aligned left.</blockquote><p>We also would like to make “not available” values stand out less than the rest of our cell values. We’ll have the attribute set the font color of these values to a light gray.</p><p>The directive needs to take the cell value as an argument so it can determine the appropriate styling to apply based on the value type.</p><p>Create the <em>style-cell.directive.ts </em>in the <em>shared </em>folder.</p><pre>// ./shared/style-cell.directive.ts<br>import { Directive, ElementRef, <br>         Input, Renderer, OnInit } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;</pre><pre><a href="http://twitter.com/Directive">@Directive</a>({ selector: &#39;[ctStyleCell]&#39;})<br>export class StyleCellDirective implements OnInit {<br>    <a href="http://twitter.com/Input">@Input</a>() ctStyleCell: string;<br>    constructor(<br>       private el: ElementRef, <br>       private renderer: Renderer) { }<br>    ngOnInit() {<br>        if (this.ctStyleCell === undefined) {<br>            this.renderer.setElementStyle(<br>                 this.el.nativeElement, <br>                 &#39;color&#39;, <br>                 &#39;#dcdcdc&#39;);<br>            this.renderer.setElementStyle(<br>                 this.el.nativeElement, <br>                 &#39;text-align&#39;, <br>                 &#39;center&#39;);<br>        }<br>        if (typeof this.ctStyleCell === &#39;number&#39;) {<br>            this.renderer.setElementStyle(<br>                 this.el.nativeElement, <br>                 &#39;text-align&#39;, <br>                 &#39;right&#39;);<br>        }<br>    }<br>}</pre><p>We must import it into our <em>SharedModule </em>before we can use it.</p><pre>// ./shared/shared.module.ts<br>...<br>import { <strong>StyleCellDirective </strong>} from &#39;./style-cell.directive&#39;;</pre><pre><a href="http://twitter.com/NgModule">@NgModule</a>({<br>    imports: [ CommonModule ],<br>    declarations: [ <br>        ...<br>        <strong>StyleCellDirective</strong><br>    ],<br>    ...</pre><p>Finally, we apply it to our table cell. We bind <strong>record[map.primaryKey] </strong>to it in order to provide it with the cell value for type checking.</p><pre>&lt;!-- ./shared/table-layout.component.html --&gt;<br>...<br>        &lt;tr *ngFor=&quot;let record of records&quot;&gt;<br>            &lt;td *ngFor=&quot;let map of columnMaps&quot;<br>                <strong>[ctStyleCell]=&quot;record[map.primaryKey]&quot;</strong>&gt;<br>                {{ record[map.primaryKey] | formatCell:map.format }}<br>            &lt;/td&gt;<br>        &lt;/tr&gt;<br>...</pre><p>The table looks pretty good now when we run the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*FLp5MAnGdbAiaCvnn1cj3A.png" /></figure><h4>Making the solution extensible— the ColumnMap class</h4><p>The final piece is to create a class that can handle all the complicated initialization logic of our column settings, applying default values as needed.</p><p>It also will handle our most challenging requirement:</p><blockquote>Find the appropriate column value when supplied objects have different property keys used to access that value. E.g. My <strong><em>Cost </em></strong>column value could be stored as <em>object.cost</em>, <em>object.total_cost, </em>or <em>object.funding</em>.</blockquote><p>As part of our planning, we wrote the following specification.</p><blockquote><strong>ColumnMap class</strong>: Constructs configuration settings for each column. Supplies the appropriate parameters to the TableLayoutComponent, FormatCellPipe, and StyleCellDirective for each column. Constructs class instances initialized with default values, if user settings are not supplied.</blockquote><p>We write this class in the <em>layout.model.ts </em>file in the <em>shared </em>folder underneath the ColumnSetting class.</p><pre>// ./shared/layout.model.ts<br>...<br>export class ColumnMap {<br>    primaryKey: string;<br>    private _header: string;<br>    private _format: string;<br>    alternativeKeys?: string[];</pre><pre>constructor ( settings ) {<br>        this.primaryKey = settings.primaryKey;<br>        this.header = settings.header;<br>        this.format = settings.format;<br>        this.alternativeKeys = settings.alternativeKeys;<br>    }<br>    set header(setting: string) {<br>        this._header = setting ? <br>            setting :<br>            this.primaryKey.slice(0, 1).toUpperCase() + <br>                this.primaryKey.replace(/_/g, &#39; &#39; ).slice(1)<br>    }<br>    get header() {<br>        return this._header;<br>    }<br>    set format(setting: string) {<br>        this._format = setting ? setting : &#39;default&#39;;<br>    }<br>    get format() {<br>        return this._format;<br>    }</pre><pre>access = function ( object: any ) {<br>        if (object[this.primaryKey] || !this.alternativeKeys) {<br>            return this.primaryKey;<br>        }<br>        for (let key of this.alternativeKeys) { <br>            if (object[key]) {<br>                return key;<br>            }<br>        }<br>        return this.primaryKey;<br>    }<br>}</pre><p>This code applies three features of TypeScript classes.</p><ol><li>Define getter and setter methods that access private variables. This allows for initialization logic to define default setting values when corresponding settings are not supplied.</li><li>Use the constructor initializes class instance properties, calling setter methods for the private variables.</li><li>Define a method, called <em>access, </em>for each class instance that can be used to look for the column value on several object properties if <em>alternativeKeys </em>are provided in the settings. This handles the case, for example — <br><em>My </em><strong><em>Cost </em></strong><em>column value could be stored as </em><strong><em>object.cost</em></strong><em>, </em><strong><em>object.total_cost</em></strong><em>, or </em><strong><em>object.funding</em></strong><em>.</em></li></ol><p>We update the <em>TableLayoutComponent </em>to take advantage of this class. Notice that it simplifies the code because we can remove the logic previously used to initialize default values from the component.</p><pre>// ./shared/table-layout.component.ts<br>import { Component, Input, OnChanges } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;<br>import { ColumnSetting, <strong>ColumnMap </strong>} from &#39;./layout.model&#39;;<br><a href="http://twitter.com/Component">@Component</a>({<br>    selector: &#39;ct-table&#39;,<br>    templateUrl: &#39;app/shared/table-layout.component.html&#39;<br>})<br>export class TableLayoutComponent implements OnChanges { <br>    <a href="http://twitter.com/Input">@Input</a>() records: any[];<br>    <a href="http://twitter.com/Input">@Input</a>() caption: string;<br>    <a href="http://twitter.com/Input">@Input</a>() settings: ColumnSetting[];<br>    columnMaps: <strong>ColumnMap[]</strong>; <br>    ngOnChanges() {<br>        if (this.settings) {<br>            <strong>this.columnMaps = this.settings<br>                .map( col =&gt; new ColumnMap(col) );</strong><br>        } else {<br>            this.columnMaps = Object.keys(this.records[0])<br>                .map( key =&gt; {<br>                    <strong>return new ColumnMap( { primaryKey: key });</strong><br>            });<br>        }<br>    }<br>}</pre><p>Update the template to use the access method on the ColumnMap instances, rather than primaryKey.</p><pre>...<br>&lt;tr *ngFor=&quot;let record of records&quot;&gt;<br>     &lt;td *ngFor=&quot;let map of columnMaps&quot;<br>         [ctStyleCell]=&quot;record[<strong>map.access(record)</strong>]&quot;&gt;<br>            {{ record[<strong>map.access(record)</strong>] | formatCell:map.format }}<br>     &lt;/td&gt;<br>&lt;/tr&gt;<br>...</pre><p>To take advantage of the additional functionality we’ve extended our table layout with, we’ll apply some additional <em>settings </em>to our columns in the <em>ProjectCenterComponent</em>.</p><pre>// ./project-center.component.ts<br>...<br>projectSettings: ColumnSetting[] = <br>      [<br>          ...<br>          {<br>              <strong>primaryKey: &#39;first_launch&#39;,</strong><br>              header: &#39;First Launch&#39;,<br>              <strong>alternativeKeys: [&#39;launch&#39;, &#39;first_flight&#39;]</strong><br>          },<br>          {<br>              primaryKey: &#39;cost&#39;,<br>              header: &#39;Cost&#39;,<br>              format: &#39;currency&#39;,<br>              <strong>alternativeKeys: [&#39;total_cost&#39;]</strong><br>          }<br>      ];<br>...</pre><p>We know that a <strong>first_launch </strong>property does not exist on our sample data set, but we set this as the <strong>primaryKey</strong> so we can see if our <em>ColumnMap </em>class will successfully check multiple <strong>alternativeKeys</strong>.</p><p>For the Space Shuttle record, the cost value we want is stored as <strong>total_cost</strong>, so we specify this in the <strong>alternativeKeys</strong>.</p><p>Running the app, we see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*fbijmppon8Uo7AROLRjCYQ.png" /></figure><p>We now see the Space Shuttle cost, and our launch dates still display as expected.</p><h4>One more test with more complicated data</h4><p>Finally, let’s see how well our <em>TableLayoutComponent</em> can handle more complex data.</p><p>Update <em>/project-center/fakedata.ts</em> as follows.</p><pre>...<br>export const PERSONNEL: Person[] = [<br>    { <br>        id: 151, <br>        name: &#39;Alan B. Shepard, Jr.&#39;, <br>        job: &#39;Astronaut&#39;, <br>        year_joined: 1959,<br>        missions: [&#39;MR-3&#39;, &#39;Apollo 14&#39;],<br>        <strong>crewWith: [<br>            {<br>                id: 175,<br>                name: &#39;Stuart Roosa&#39;<br>            },<br>            {<br>                id: 176,<br>                name: &#39;Edgar Mitchell&#39;<br>            }<br>        ]</strong><br>    },<br>    ...<br>    <strong>{ <br>        id: 161, <br>        name: &#39;James A. Lovell&#39;, <br>        job: &#39;Astronaut&#39;, <br>        year_joined: 1962,<br>        missions: [&#39;Gemini 7&#39;, &#39;Gemini 12&#39;, <br>                   &#39;Apollo 8&#39;, &#39;Apollo 13&#39;], <br>        manager: {<br>            id: 157,<br>            name: &#39;Deke Slayton&#39;<br>        }<br>    }</strong><br>];</pre><p>We update the record of <strong>Alan Shepard </strong>to include his crew mates on the Apollo 14 mission as an array of objects. We add a new record for <strong>James Lovell</strong> who was on four missions. We identify his manager, Chief Astronaut Deke Slayton, in a nested object. Remember that we setup our pipe to return the <em>name </em>property of nested objects. However, we never tested if it worked.</p><p>Add the following settings in <em>ProjectCenterComponent</em>.</p><pre>// ./project-center/project-center.component.ts<br>...<br>personnelSettings: ColumnSetting[] = <br>       [<br>            {  primaryKey: &#39;name&#39; },<br>            {  primaryKey: &#39;year_joined&#39;, header: &#39;Joined&#39; },<br>            {  primaryKey: &#39;missions&#39; },<br>            {  primaryKey: &#39;manager&#39;  },<br>            {  primaryKey: &#39;crewWith&#39;, header: &#39;Crew mates&#39;}<br>        ];<br>...</pre><p>Bind the settings in the template.</p><pre>&lt;!-- ./project-center/project-center.component.html --&gt;<br>    ...<br>    &lt;ct-table [records]=&quot;projects&quot;<br>              [caption]=&quot;&#39;NASA Projects&#39;&quot;<br>              [settings]=&quot;projectSettings&quot;&gt;<br>    &lt;/ct-table&gt;<br>    &lt;ct-table [records]=&quot;people&quot;<br>              [caption]=&quot;&#39;NASA Astronauts&#39;&quot;<br>              <strong>[settings]=&quot;personnelSettings&quot;</strong>&gt;<br>    &lt;/ct-table&gt;</pre><p>The astronauts table now looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w5A4apZrJuLLiSRwhP-Ebg.png" /></figure><p>We now have a good general-purpose component for tables in our Angular 2 project. There’s a lot that can be done to extend it, and we have a solid architecture as a basis. We’ll leave the demonstration at this for now. I will continue to post articles that follow up on this example.</p><p>Thank you for following.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adf6bba3b498" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular2: Module architecture and example seed project]]></title>
            <link>https://medium.com/@ct7/angular2-module-architecture-and-example-seed-project-35b7410264f5?source=rss-168b2940d972------2</link>
            <guid isPermaLink="false">https://medium.com/p/35b7410264f5</guid>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Thomas Rundle]]></dc:creator>
            <pubDate>Fri, 04 Nov 2016 16:53:45 GMT</pubDate>
            <atom:updated>2016-11-04T16:53:45.247Z</atom:updated>
            <content:encoded><![CDATA[<p>I will write several Angular 2 tutorials based on Angular 2 projects I’ve developed. The intended audience is developers who have already had a thorough introduction to Angular 2 and are looking to master concepts while building robust, reusable modules that can be leveraged for future billable projects.</p><p>Perhaps like me, there are others who have been through most of the Angular team’s documentation and even some of the source, but are still asking “Just how well do I know this? Am I ready to build enterprise applications with it?”</p><p>Building a large, feature rich project is the only way to find out. I start small by building a seed project based on the <a href="https://angular.io/docs/ts/latest/quickstart.html">Quickstart Guide</a> on <a href="http://angular.io/">angular.io</a>.</p><p>Of course, there are several ways to setup a new Angular 2 project. You may prefer <a href="https://webpack.github.io/">webpack </a>over <a href="https://github.com/systemjs/systemjs">SystemJS</a>. You may like the <a href="https://cli.angular.io/">Angular CLI</a>. I want my tutorials to serve as an extension of the excellent work the Angular team has done on angular.io. As such, I will use their <a href="https://angular.io/docs/ts/latest/quickstart.html">Quickstart Guide</a> and follow all architectural recommendations included in their documentation.</p><p>If you are new to Angular 2, I highly recommend the <a href="https://angular.io/docs/ts/latest/">Angular Docs</a>, <a href="https://www.manning.com/books/angular-2-development-with-typescript">Angular 2 Development with TypeScript</a> (early access), and <a href="https://vsavkin.com/">Victor Savkin’s blog</a>. These have been my go-to resources for the past several months.</p><p>This project establishes the following module architecture based on guidelines in the <a href="https://angular.io/docs/ts/latest/guide/ngmodule.html">documentation for NgModule</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UZIwFTUrkaFfZi8Tx8TENg.png" /></figure><h4>Create the seed project</h4><blockquote>You can also download the seed project from <a href="https://github.com/conduitl/ng-savant/tree/master/seed">my GitHub rep</a>o.</blockquote><ol><li><strong>Follow the </strong><a href="https://angular.io/docs/ts/latest/quickstart.html"><strong>Quickstart Guide</strong></a><strong>.</strong></li></ol><p>Once you’ve followed these steps, your working directory will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/1*446yEIQkszuxGi3R8hhDbg.png" /></figure><p>For simple styling, load Bootstrap into index.html using the CDN provided at <a href="http://getbootstrap.com/">getbootstrap.com</a>.</p><pre>&lt;!-- Bootstrap compiled and minified CSS --&gt;<br>&lt;link rel=”stylesheet” href=”<a href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css</a>&quot;&gt;</pre><p><strong>2. Setup CoreModule.</strong></p><blockquote><em>The CoreModule is where we include application wide components and services. We import this module into AppModule and nowhere else. Components included statically on all your views, such as app navigation, are ideal candidates for inclusion in the CoreModule.</em></blockquote><blockquote><em>Likewise, services that will be utilized by the entire app, such as a UserService storing user profiles and handling authentication, belong in the CoreModule.</em></blockquote><p>Create the <em>core </em>folder and put three new files inside it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*m5C_6W7DqyeojAIioauANw.png" /></figure><pre>// core/core.module.ts<br>import { NgModule } from ‘<a href="http://twitter.com/angular/core">@angular/core</a>’;<br>import { CommonModule } from ‘<a href="http://twitter.com/angular/common">@angular/common</a>’;</pre><pre>import { NavbarComponent } from ‘./navbar.component’;</pre><pre><a href="http://twitter.com/NgModule">@NgModule</a>({<br> imports: [ CommonModule ],<br> declarations: [ NavbarComponent ],<br> exports: [ NavbarComponent ],<br> providers: []<br>})<br>export class CoreModule { }</pre><p>The CoreModule declares and exports the NavbarComponent. This allows the &lt;ct-navbar&gt; selector to be placed on the AppComponent template.</p><pre>// core/navbar.component.ts<br>import { Component } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;</pre><pre><a href="http://twitter.com/Component">@Component</a>({<br>    selector: &#39;ct-navbar&#39;,<br>    templateUrl: &#39;app/core/navbar.component.html&#39;<br>})<br>export class NavbarComponent { }</pre><p>The Angular docs recommend adding a prefix to the selectors on your component to future-proof your application against possible conflicts with future HTML specifications. The prefix I use happens to be “<em>ct”. </em>Do not use <em>“ng”</em> as a prefix, because this prefix should be reserved for Angular built-in components.</p><pre>// core/navbar.component.html<br>&lt;nav class=&quot;navbar navbar-inverse navbar-fixed-top&quot;&gt;<br>    &lt;div class=&quot;container-fluid&quot;&gt;<br>        &lt;div class=&quot;navbar-header&quot;&gt;<br>            &lt;a class=&quot;navbar-brand&quot;&gt;Project Manager&lt;/a&gt;<br>        &lt;/div&gt;<br>        &lt;ul class=&quot;nav navbar-nav&quot;&gt;<br>            &lt;li&gt;&lt;a&gt;Link 1&lt;/a&gt;&lt;/li&gt;<br>            &lt;li&gt;&lt;a&gt;Link 2&lt;/a&gt;&lt;/li&gt;<br>        &lt;/ul&gt;<br>    &lt;/div&gt;<br>&lt;/nav&gt;</pre><p>Now, update the AppModule to import the CoreModule and insert <br><strong>&lt;ct-navbar&gt;</strong> into the the AppComponent template.</p><pre>// app.module.ts<br>import { NgModule }      from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;<br>import { BrowserModule } from &#39;<a href="http://twitter.com/angular/platform-browser">@angular/platform-browser</a>&#39;;</pre><pre><strong>import { CoreModule } from &#39;./core/core.module&#39;;</strong></pre><pre>import { AppComponent }   from &#39;./app.component&#39;;<br><a href="http://twitter.com/NgModule">@NgModule</a>({<br>  imports:      [ <br>    BrowserModule,<br>    <strong>CoreModule</strong>  <br>  ],<br>  declarations: [ AppComponent ],<br>  bootstrap:    [ AppComponent ]<br>})<br>export class AppModule { }</pre><p>I prefer separate HTML files rather than inline templates in most cases. I adjust the AppComponent accordingly.</p><pre>// app.component.ts<br>import { Component } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;<br><a href="http://twitter.com/Component">@Component</a>({<br>  selector: &#39;my-app&#39;,<br>  <strong>templateUrl: &#39;app/app.component.html&#39;</strong><br>})<br>export class AppComponent { }</pre><p>Insert the NavbarComponent selector into the AppComponent template.</p><pre>// app.component.html<br>&lt;ct-navbar&gt;&lt;/ct-navbar&gt;</pre><p>The running application now looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rLAC9cThLLXjBwAvDx6TAA.png" /></figure><p>This is a good start for the CoreModule. Now lets work on the SharedModule.</p><p><strong>3. Setup SharedModule.</strong></p><blockquote><em>The SharedModule contains components that will be reused in two or more feature modules. We will setup the SharedModule for this seed project with one component. A TableLayoutComponent is just the kind of component that is likely to be reused in many parts of the application.</em></blockquote><p>Create the <em>shared </em>folder and create three files inside it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*9kOGXHpBkxDvYTL0r4Pmww.png" /></figure><pre>// shared/shared.module.ts<br>import { NgModule } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;<br>import { CommonModule } from &#39;<a href="http://twitter.com/angular/common">@angular/common</a>&#39;;</pre><pre>import { TableLayoutComponent } from &#39;./table-layout.component&#39;;</pre><pre><a href="http://twitter.com/NgModule">@NgModule</a>({<br>    imports: [ CommonModule ],<br>    declarations: [ TableLayoutComponent ],<br>    exports: [<br>        CommonModule, <br>        TableLayoutComponent <br>    ]<br>})<br>export class SharedModule { }</pre><p>By importing and then re-exporting CommonModule, we’ll save ourselves from needing to import CommonModule into any feature modules that import this SharedModule. We declare and export TableLayoutComponent. This component contains a template we wish to make available to several modules later on.</p><pre>// shared/table-layout.component.ts<br>import { Component } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;</pre><pre><a href="http://twitter.com/Component">@Component</a>({<br>    selector: &#39;ct-table&#39;,<br>    templateUrl: &#39;app/shared/table-layout.component.html&#39;<br>})<br>export class TableLayoutComponent { }</pre><p>The template contains an example 3 x 3 table with Bootstrap styling.</p><pre>// shared/table-layout.component.html<br>&lt;table class=&quot;table&quot;&gt;<br>    &lt;caption&gt;Table&lt;/caption&gt;<br>    &lt;thead&gt;<br>        &lt;tr&gt;<br>            &lt;th&gt;Column 1&lt;/th&gt;<br>            &lt;th&gt;Column 2&lt;/th&gt;<br>            &lt;th&gt;Column 3&lt;/th&gt;<br>        &lt;/tr&gt;<br>    &lt;/thead&gt;<br>    &lt;tbody&gt;<br>        &lt;tr&gt;<br>            &lt;td&gt;Some value&lt;/td&gt;<br>            &lt;td&gt;Some value&lt;/td&gt;<br>            &lt;td&gt;Some value&lt;/td&gt;<br>        &lt;/tr&gt;<br>        &lt;tr&gt;<br>            &lt;td&gt;Some value&lt;/td&gt;<br>            &lt;td&gt;Some value&lt;/td&gt;<br>            &lt;td&gt;Some value&lt;/td&gt;<br>        &lt;/tr&gt;<br>        &lt;tr&gt;<br>            &lt;td&gt;Some value&lt;/td&gt;<br>            &lt;td&gt;Some value&lt;/td&gt;<br>            &lt;td&gt;Some value&lt;/td&gt;<br>        &lt;/tr&gt;<br>    &lt;/tbody&gt;<br>&lt;/table&gt;</pre><p>That’s it for the SharedModule for now. To make use of it, we need a feature module. Creating this feature module is the last step in this article.</p><blockquote>Note: For this example template to be useful, the table needs to be dynamically constructed based on data sent to it. In a follow up article, I will demonstrate how to build out this starter component for a dynamic table layout.</blockquote><p><strong>4. Leverage the SharedModule within a feature module.</strong></p><blockquote><em>The rest of the Angular 2 application will be contained in feature modules. The Angular docs describe feature modules as collections of related functionality that are imported into the root module.</em></blockquote><p>As an example, we’ll create a feature called ProjectCenterModule.</p><p>Create a <em>project-center </em>folder with three new files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/229/1*j_PRcbMS2GiYmvhkckfLVQ.png" /></figure><pre>// project-center/project-center.module.ts<br>import { NgModule } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;</pre><pre>import { SharedModule } from &#39;../shared/shared.module&#39;;</pre><pre>import { ProjectCenterComponent } from &#39;./project-center.component&#39;;</pre><pre><a href="http://twitter.com/NgModule">@NgModule</a>({<br>    imports: [ SharedModule ],<br>    declarations: [ ProjectCenterComponent ],<br>    providers: [],<br>    exports: [ ProjectCenterComponent ]<br>})<br>export class ProjectCenterModule { }</pre><p>Notice that we imported the SharedModule into our ProjectCenterModule.</p><pre>// project-center/project-center.component.ts<br>import { Component } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;</pre><pre><a href="http://twitter.com/Component">@Component</a>({<br>    selector: &#39;ct-project-center&#39;,<br>    templateUrl: &#39;app/project-center/project-center.component.html&#39;<br>})<br>export class ProjectCenterComponent {<br>    title: string = &#39;Project Center&#39;;<br>}</pre><p>The template implements the &lt;ct-table&gt; selector made available through the SharedModule.</p><pre>// project-center/project-center.component.html<br>&lt;div class=&quot;container-fluid&quot;&gt;<br>    &lt;div class=&quot;page-header&quot;&gt;<br>        &lt;h1&gt;{{ title }}&lt;/h1&gt;<br>    &lt;/div&gt;<br>    &lt;ct-table&gt;&lt;/ct-table&gt;<br>&lt;/div&gt;</pre><p>Before we run the app, AppModule needs to be updated to import ProjectCenterModule.</p><pre>// app.module.ts<br>import { NgModule }      from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;<br>import { BrowserModule } from &#39;<a href="http://twitter.com/angular/platform-browser">@angular/platform-browser</a>&#39;;</pre><pre>import { CoreModule } from &#39;./core/core.module&#39;;<br><strong>import { ProjectCenterModule } from &#39;./project-center/project-center.module&#39;;</strong></pre><pre>import { AppComponent }   from &#39;./app.component&#39;;<br><a href="http://twitter.com/NgModule">@NgModule</a>({<br>  imports:      [ <br>    BrowserModule,<br>    CoreModule,<br>    <strong>ProjectCenterModule</strong><br>  ],<br>  declarations: [ AppComponent ],<br>  bootstrap:    [ AppComponent ]<br>})<br>export class AppModule { }</pre><p>And insert the &lt;ct-project-center&gt; selector into the AppComponent template.</p><pre>// app.component.html<br>&lt;ct-navbar&gt;&lt;/ct-navbar&gt;<br><strong>&lt;ct-project-center&gt;&lt;/ct-project-center&gt;</strong></pre><p>Run the app and this is what you’ll see.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oSmzYdOHHJmg0P0mfm4jXw.png" /></figure><p>Not terribly interesting, but it is a good baseline from where we can explore more advanced topics.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35b7410264f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>