Rules to Better Angular 2

​​Angular 2 is a great improvement on Angular 1, however it also comes with a completely new set of rules and guidelines to get you up and running with the least pain.

Read Rules to Getting Started with Angular 2

Hold on a second! How would you like to view this content?
Just the title! A brief blurb! Gimme everything!
  1. Do you know how to get started learning Angular?

    The best way to get started using Angular is by checking out the Rules to Getting Started with Angular.

  2. Do you use the best JavaScript libraries?

    It's important to keep on top of what the best JavaScript frameworks are. 

    In this explosive video Ben Cull, SSW Solution Architect, will bombard you with what are the best JavaScript Frameworks to use in 2016.

     


  3. Do you have a pleasant development workflow?

    When dealing with client side development – especially when transpiling TypeScript – it is common to have to wait for several seconds between writing code, and seeing the results.

    This adds up quickly – if you have to wait for 5 seconds every 3 minutes, you've spent 13 minutes of your day just waiting. This is a conservative estimate - we change code much more frequently than every 3 minutes!

    A naïve development experience is as follows:

    1. Make a code change using a misconfigured IDE
      • See errors everywhere as you type (even though the code is perfectly fine)
      • Inaccurate IntelliSense information
    2. Compile the code
      • Since the TypeScript compilation task is often part of the project build, this is a common way to recompile to JavaScript
    3. Run a gulp task to copy files around appropriately
      • This often takes a few seconds to run, especially if it “cleans” the folder beforehand
    4. Refresh the page
      • Depending on the setup, this may take anywhere from milliseconds to seconds
    5. Click around until the app is in the right state to test the functionality
      • If there is too much built-up state, and no routes set up, this chews up time
    Bad example - Many hours each week are wasted just waiting for the code you wrote to run 


    A more ideal workflow is:

    1. Make the change using a properly configured IDE
      • One that only shows errors when they’re appropriate
      • Intellisense shows everything available, and nothing more
    2. Refresh the page (maybe)
      • With well set up watches for compilation and appropriate use of BrowserLink or LiveReload, this is very fast
      • With proper bundling, the initial page load is also fast in development environments.
    3. Already be at the component required, ready to check it works
    Good example - No time is wasted doing repetitive and slow tasks


    Remember: Spending 4 hours setting up a good dev experience will pay for itself within the week, and make your work like much happier.

    Guidelines to follow:

    • Ensure that only the files that are changed need to be compiled – TypeScript handles this quite well with --watch
    • Avoid the use of task runners (eg. gulp) as part of your development flow. A few watches should be all you need. Save the task runners for release builds
    • Consider separate index pages for production and development, using the dev libraries for development, and minified/bundled ones for production
    • Use module loaders (eg. SystemJS) to manage dependencies and their associated bundlers/builders for releases
    • Load 3rd party modules (eg. Angular2 and Rx) as a bundle, not as their individual files – speed up development first-page load
    • Think about your routing – a refresh should almost always return the page to the exact same state or at the very least, the same screen
    • Most importantly, be unsatisfied - if things are slow, fix it. If you constantly have to manually close IISExpress to run your app, find out why and fix it! You will save everyone time in the long run
  4. Do you know the best sample applications?

    Before starting a software project and evaluating a new technology, it is important to know what the best practices are. The easiest way to get up and running is by looking at a sample application. Below are a list of sample applications that we’ve curated and given our seal of approval.

    SQL Server (2014 and below)

    SQL Server 2016 and Azure SQL Database

    ASP.NET MVC + WebAPI

    SPA

    AngularJS

    Angular

    2

  5. Do you know the best Packages and Modules to use with Angular 2?

    ​You can improve your Angular 2 development experience by using some of these recommended packages and modules.

    We recommend you use NPM to include them.

    Lodash
    A modern JavaScript utility library delivering modularity, performance, & extras.

    https://lodash.com

    Angular2 Bootstrap

    Angular2 components for bootstrap components.

    http://valor-software.com/ng2-bootstrap/


    Angular2 Bootstrap Modal Popups
    Bootstrap themed modal popups for Angular2

    https://github.com/dougludlow/ng2-bs3-modal


    OpenID Token Manager
    Handles management of OpenID authentication and tokens

    https://github.com/IdentityModel/oidc-token-manager

     

    Inline templates gulp task
    A gulp task to inline template HTML into the JS file for faster loading

    https://github.com/ludohenin/gulp-inline-ng2-template

     

    C# POCO to TSD
    A gulp task to inline template HTML into the JS file for faster loading

    https://www.npmjs.com/package/gulp-typescript-cs-poco

  6. Do you use Typescript for your Angular 2 Applications?

    Typescript is the best choice ​when writing Angular 2 applications. Angular 2 is even written in Typescript itself! 

    ​Typescript allows you to strongly type your javascript code, as well as use the new ES6+ specifications.

    You can start learning more about typescipt at http://www.typescriptlang.org/​

    You should also check out SSW TV Videos on Typescript

  7. Do you write small components?

    The Single Responsibility Principle  is a well understood, and well-accepted tenant of good code design.  It states that a class should do one thing, and do it well – and an Angular2 component is no exception.

    When designing components, keep them small, modular and reusable. For example, if you have a menu, put it into a menu component, don’t put it in your app component.

    comp-1.png
    Figure: Bad example - Having just 3 components for the page makes it difficult to reuse, maintain and test.
    comp-2.png
    Figure: Good example - Splitting up the page into 11 components means they are small and targeted - and thus easy to maintain and test. Components can be reused on other pages
  8. Do you use client-side routing?

    Single page applications (SPAs) are getting more and more popular, and for good reason – a better and faster user experience, reduced server load and encourages good API separation.

    But have you ever visited a website, thought “I’ll refresh that” and then got taken back to the home screen? Or tried to copy or bookmark the URL, only to find it’s just “/Home”? This happens when client side routing hasn’t been implemented properly, and is a big hit to a site’s usability.

    This is easily fixed with Angular 2’s routing capabilities, and implementing it in your SPA will confer several advantages:​

    • URLs can be copy-pasted and shared
    • Page refreshes work as expected
    • Less prone to errors
    • Better separation of concerns (navigation vs page state) 
    client-side-bad.png
    Figure: Bad example - The blog post component is choosing components based on the state of the component

    A better way is to set up routes, and use a router (the first-party component router is great for this) to manage your components:

    client-side-good.png
    Good: Setting up declarative routes and outlets gives a good user experience, persistent URLs and fewer moving parts
  9. Do you generate interfaces for your DTOs?

    Inevitably, our well-engineered Angular 2 application will need to send and receive data from a service of some sort – usually a Web API. A common mistake people make when doing this is using typescript’s built in any type for these services, which offers no type safety whatsoever.

    dtogs-bad.png
    Figure: Bad example - The "any" type is used as the DTO for this service. There is no type safety.

    One step better is to manually create interfaces for the DTOs. This gives type safety, but still means a lot of manual, tedious work to generate the interfaces.

    dtogs-ok.png
    Figure: Better example - Manually coded interface ensures any object passed to the service is in the correct format

    But this still doesn’t give safety over-the-wire – if the server side model changes, a developer has to remember to update it here, and hope that there are no typos.  This is also extra effort to perform something mindlessly repetitive – something a machine is much better at doing.  And we are programmers, right?

    An example of such a generator is gulp-typescript-cs-poco ​, but there are many out there.

    dtos-good.png
    Figure: Good example - Writing a small bit of code means I don’t have to write a lot of code every time I change a DTO
  10. Do you avoid the DOM in your components?

    W​ith the introduction of Angular2, there has been a big push in ensuring the DOM stays out of your JavaScript code.  It is designed in such a way that an existing angular2 application can be ported to another target by simple replacing the template and template loader.  Projects such as Angular2 React Native Renderer  leverages this to allow native mobile app development in Angular2. 

    For this to work well, there has to be a clear separation between the component’s logic and the component’s view – which means avoiding using the DOM in your component’s code.  This gives a few further advantages:

    • Smaller component code making it easier to maintain
    • Faster running and easier to write unit tests
    • Easier for designers to get involved​

    This means that the component's state must expose things that are useful to the template as public properties or fields, and the template should read these fields to draw itself.​

    dom1.png
    This component manipulates the DOM directly to show and hide the menu
    dom2.png
    This component sets component state, which the template can use.  It is simpler, more descriptive and easier to test
  11. Do you use lodash to perform your daily _.foreach?

    In a nutshell, Lo-Dash is a super useful library that gives you access to over 100 extremely performant functions to help you avoid reinventing the wheel whilst writing JavaScript.

    You can get lodash from GitHub repositorycdnjs or via NPM. Once done you can include a reference in your HTML.

    ​A simple example of the power of lodash is this snippet of code which is looping through a shared Kendo datasource that is being used in large Kendo grid. The shared datasource has many duplicates and this snippet does four things:

    1. Removes duplicate account numbers
    2. Plucks out only the account numbers into a new array
    3. Sorts the array by alphabetical order
    4. Removes blank entries

    This new simplified array of account numbers was then used in a dropdown to filter the Kendo grid. This single line saves a call to the database for another array of data and populates the dropdown with the same shared datasource. This would be a pain to write with vanilla javascript and difficult to read.

    this.accountNumberDropDownData = _.chain(this.sharedDataSource).pluck('AccountNumber').uniq().sortBy().value();

    Good example - Simple one line of TypeScript which would take many line of code without lodash

    If you have been into JavaScript development for a while you may of also heard about underscore.js which is very similar to Lo-Dash but has some fundamental differences.

    I created Lo-Dash to provide more consistent cross-environment iteration support for arrays, strings, objects, and arguments objects1. It has since become a superset of Underscore, providing more consistent API behavior, more features (like AMD support, deep clone, and deep merge), more thorough documentation and unit tests (tests which run in Node, Ringo, Rhino, Narwhal, PhantomJS, and browsers), better overall performance and optimizations for large arrays/object iteration, and more flexibility with custom builds and template pre-compilation utilities.

    — John-David Dalton

    Further reading:

    1. https://lodash.com
    2. http://underscorejs.org
  12. Do you know the best UI framework for Angular 2?

    When you start a new project you need to choose the essential ingredients that you are going to use for your app.

    One of the main choices is the tools you will use for your user interface.​


    ​​bad-bootstrap.png
    Figure: Bad Example - Bootstrap has been the recommended UI framework for the web for years, but is not written by the Angular team
    angular-material.png​​
    Figure: Good Example - Angular Material is built by the Angular team, has first class Angular integration and implements modern UI best practices

  13. Do you know the best tools to debug Javascript?

    ​Debugging JavaScript application can be difficult. Having to console.log results can make for a slow and cumbersome development experience. There are five ways you can debug a JavaScript application without leaning on console.log() as your main tool.​

    Options for Debugging JavaScript applications

    1. Debug your JavaScript using console.log()
      While this is a valid approach it should only be utilized for the simplest of manual debugging tests as they are slow, you have to re-run the app every time, do not allow you to change state mid-flight and developers sometimes forget to clean up after themselves and the code becomes riddled with console.log statements.

      debug-js-1.png
      Bad code - Using console.log() to debug your JavaScript

    2. Debug in the browser with a breakpoint
      Chrome is by far the most popular browser for the average web developer followed by FireFox, but all the major browsers have a debugging tool.
      debug-js-2.png
      Figure: Old school JavaScript debugging with Chrome Dev Tools is still the best and most versatile tool
    3. Debug in an IDE
      It is often more effort than it is worth to debug JavaScrtipt in your IDE and it is still not very popular. If your app is a Server Side NodeJS JavaScript app then it is very different since this type of JavaScript app does not run in the browser and this is what the IDE is designed for. 
      • Visual Studio Code Chome Debugger - Painful to set up source maps for advanced JavaScript applications that run in memory dev servers like WebPack Dev Server.
      • Visual Studio 2015 - Only works with TypeScript in Internet Explorer
      debug-js-3.png
      Figure: Visual Studio Chrome Debugger with breakpoint set
    4. Time Travel Debugging with Redux
      Using tools like ngrx's store dev tools . You can traverse back and forth between states with excellent UI tools. Debugging through your states is much better than just debugging the current state but also to be able to see the actions triggered to change state.
      debug-js-4.png
      Figure: Example of redux based time travel debugging
    5. Hot Module Reloading
      The problem with the above approaches is every time you make a change to your code you need to reload the website and navigate back to the page and state of that page again and again to repeat your manual test. Hot Module Replacement (HMR) exchanges, adds, or removes modules while an application is running without a page reload.
      debug-js-5.png
      Figure: Hot module reloader documentation from WebPack website
  14. Angular - Do you know the stuff to install?

    It is suggested using cli.angular.io to start an Angular2 project especially when learning as it is the easiest way to both get started and also follow best practices.

    If you are new to Angular we recommend you use VSCode versus Visual Studio 2015/17 as the TypeScript support and project directory (without a Visual Studio Project) is easier.

    angular-quick-start.png
    Figure: Bad example - Don 't use the Angular QuickStart because you have to setup everything manually (the CLI gives you it all automatically)
    1. Install nodejs V4 and npm V3 or higher https://nodejs.org/en
      Check you have the right versions:

       node -v
       npm -v
       npm -g ls --depth=0

      Note: If you do not have the right version of node or npm, it is best to uninstall then and reinstall them and your global npm packages. Using the second command below you can check which global npm packages you have installed so that you can reinstall them afterward.
    2. Install git https://git-scm.com Check you have git: 

      git --version

    3. Install latest Angular CLI [cli.angular.io]cli.angular.io

      Check you have the latest version:

      ng -v
      npm uninstall -g @angular/cli
      npm cache clean
      npm install -g @angular/cli

    4. Troubleshooting
      If you get node gyp errors follow instructions here https://github.com/nodejs/node-gyp
      If you get permission errors follow instructions here https://docs.npmjs.com/getting-started/fixing-npm-permissions  

    5. We recommend if you do not have a great TypeScript enabled IDE yet that you use http://code.visualstudio.com

  15. Do you know to separate your Angular components into container and presentational components?

    ​​​There are two types of components 'dumb' and 'smart' components. Dumb components normally have no dependencies and no logic and just have @Inputs() and @Outputs(). Smart components are their parent components that would have multiple dependencies and logic but not necessarily an HTML template.​

    ​​Aiming to keep the components that display data 'dumb' makes them much easy to reuse in your application and less buggy, but many people do not like the terms smart and dumb components as a dumb component may just have less logic versus none. Many people and SSW included are preferring the terms container and presentational components for these reasons.​​​

    company-list-table.component.ts
    @Component({
        selector: 'fbc-company-list-table',
        template: `
         <table id="company-list-table" class="table table-hover table-striped company-list-table-component">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Phone</th>
                        <th>Email</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                   <tr class="item" *ngFor="let company of companies">
                        <td>{{company.name}}</td>
                        <td>{{company.phone}}</td>
                        <td>{{company.email}}</td>
                        <td class="button-column">
                            <button routerLink="/company/detail/{{company.id}}" class="btn btn-default" >Details</button>
                            <button routerLink="/company/edit/{{company.id}}" class="btn btn-default" >Edit</button>
                            <button (click)="confirmDelete(company)" class="btn btn-default">Delete</button>
                        </td>
                    </tr>
                </tbody>
            </table>
        `
    })
    export class CompanyListTableComponent {
        @Input() companies: Company[] = [<Company>{}];
        @Output() deleteCompanySelected = new EventEmitter<number>();
                this.deleteCompanySelected.emit(company.id);
        }
    }

    ​Figure: Good example of a presenta​​tional component with no injected dependencies​