Two years with Angular and loving it

综合技术 2018-03-07

© Shutterstock / Paccione

Angular has all sorts of excellent features that keep developers happy. In this article, Yakov Fain goes over the Angular framework and explains why he’s still satisfied with switching to this framework years later.

I started working with Angular 2 framework in the summer of 2015. This framework was in Alpha at the time, and our company (Farata Systems) was actively looking for a JavaScript framework to replace the front end of a large app written using the Adobe Flex framework. By that time we already tried Ext JS and Angular JS and we didn’t like any of those frameworks. When Angular 2 was announced, we liked the combination of its component-based architecture and statically typed TypeScript with good IDE support. Two years later, we’re very happy with our choice, and in this article, I’ll give you a high-level overview of the Angular framework.

Your app is a tree of loosely-coupled components

When the developer receives a prototype of the Web design of the future app, he or she starts with splitting it up into a set of components. Any Angular app always has a top-level component, which may include child components, which in turn may include their children. Say, you’d need to re-write the Twitter app in Angular. Split it into components.

Figure 1: The Twitter app in Angular

The top-level component with the red border encompasses multiple child components. In the middle, you can see a New Tweet component on top and two instances of the Tweet component, which in turn has child components for reply, retweet, like, and direct messaging.

A parent component can pass the data to its child by binding the values to the child’s component property. A child component has no knowledge of where the data came from. A child component can pass the data to its parent (without knowing who the parent is) by emitting events. This architecture makes components self-contained and reusable.

Clean separation between UI and business logic

A component is a TypeScript class annotated with a decorator @Component where you specify the component’s HTML and CSS. You can specify them either inline or in separate files. Here’s an example of a component with the inline template and styles:

@Component({
  selector: 'home',
  template: `
Home Component
`, styles: [`.home {background: red; padding: 15px 0 0 30px; height: 80px; width:70%; font-size: 30px; float:left;}`]}) export class HomeComponent { // Implement business logic here }

As your template or styles grow in size, you can keep them in separate files:

@Component({
  selector: 'home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
export class HomeComponent {
}

Client-side navigation with the router

Angular is a good fit for creating single-page apps (SPA). The entire browser page is not getting refreshed – only the page fragments are getting replaced as the user interacts with your app. The app navigation is supported by the Router module. Within the component’s template, you declare one (or more) area where different views will be rendered as a response to the user interaction or programmatic events. For example, in the Twitter’s app you can designate the middle portion to be a , and if the user, say, clicks on the Notifications menu, another component will be rendered in this area.

Figure 2: Router Outlet in the Twitter app

Modularization

You can and should modularize your app, as Angular supports it nicely. Your app should have a root module with the minimal core functionality, and your app features should be implemented in separate modules, e.g. Billing module, Shipping module et al. Moreover, these modules can be loaded lazily to minimize the initial size of the app. For example, the landing page of your app may load the code of the Billing module only after the user clicks on the Billing button. The Angular router allows you to specify a preloading strategy so the feature modules can be loaded in the background while the user starts interacting with your app.

Dependency injection

While components are used for UI rendering, services are used for handling data and implementing business logic. Create a class ProductService and ask Angular to inject it into the ProductComponent. It’s as simple as specifying the ProductService type (a.k.a token) in the constructor of your component, and you won’t need to use the new operator:

@Component(...)
class ProductComponent{

  constructor (productService: ProductService){ }

  onClick(){
    this.productService.getProducts();
  }
}

Here, we use the injected service in the click event handler.

TypeScript and ECMAScript

TypeScript is the recommended language for programming Angular apps. It’s a superset of JavaScript that introduces static typing. If you declare variables with types (it’s optional), your IDE will offer you autocomplete, and you’ll see your errors highlighted with a red squiggly line during before the runtime. Based on our experience in developing real-world projects, TypeScript makes software developers a lot more productive compared to JavaScript. several IDEs offer great TypeScript support.

Typescript is easy to learn for anyone who knows Java, C#, C++ or other object-oriented languages. The language supports classes, interfaces, inheritance, generics and more. You program in TypeScript and then compile the code into JavaScript, which all browsers understand. Take a look at the next screenshot and compare the code you write in TypeScript (shown on the left) and its ES5 equivalent (on the right). I prefer the TypeScript version.

Figure 3: TypeScript and ES5

JavaScript is the most popular language that implements the ECMAScript (ES) spec. All browsers support the ECMAScript 5 syntax. Most modern browsers already support ES6 , which introduced lots of handy features including classes. ES7 and ES8 didn’t dramatically change the syntax, but the async-await support is a major improvement there. Can you use all latest ES features in your code today without worrying that some of the users of your app still use the browsers that only support ES5? Yes, you can, if you program in TypeScript.

And the best part is that TypeScript follows the ES standards, which means that you can use the newest ES features today without the browsers will start supporting them. By using a compiler’s option you specify the target ES syntax and compile your TypeScript code into the ES5 syntax. If you’re sure that your users work with the browsers that support a newer ES version, just change the compilation target option to generate a more modern JavaScript.

Forms API

It’s hard to imagine a commercial web app that doesn’t use forms. At the very minimum, an app needs a login form.

Every form has a model object behind it, which stores the data entered by the user in a form. Angular offers two flavors of Forms API: template-driven and reactive. The former allows you to create forms and their models without writing any code in TypeScript. All you need is to mark HTML form elements with special directives.

For a more advanced work with forms, use the reactive Forms API. You’ll be explicitly creating the model object in TypeScript, which gives you more control in working with forms.

Both template-driven and reactive Forms APIs allow you to used built-in validators or create custom ones to ensure that the user’s input is valid. If you want to perform validation on the server, Forms API supports asynchronous validators.

SEE ALSO: Angular 2018 roadmap includes Ivy Renderer, Angular Elements, Bazel and more

Reactive programming

Over the last years, libraries of reactive extensions (RX) became popular in many technologies. They offer means for handling observable data pushed by some data provider (mouse events, sensors, sockets, UI components et al.) Such libraries include a rich set of composable operators that can manipulate the data values as they move from the data provider to its subscriber(s). Angular comes with the JavaScript library called RxJS and you can use either observable provided by various Angular APIs or create your own.

Imagine that the user enters the value of the stock symbol in the input control searchInput. The following code fragment subscribes to the observable data stream valueChanges produced by the form control and makes a request to a function to get the price of the selected stock. To minimize the number of requests to the server, we apply the debounceTime operator so the function getStockQuoteFromServer() will be invoked only if the value in the input control doesn’t change during 500 milliseconds.

this.searchInput.valueChanges
  .debounceTime(500)
  .subscribe(stock => this.getStockQuoteFromServer(stock));
 }

This code is concise, but be prepared to spend some time learning how RxJS works. In this case, I just used one operator debounceTime between the data provider and subscriber, but I could have used any number of operators (e.g. map, filter et al) there.

Modern-looking UI

Lots of the production-grade web apps use super-popular styling library Bootstrap, and you can use it in your Angular apps as well. Bootstrap supports theming, offers you a number of ready to use UI controls and supports responsive web design (RWD) that allows changing the app layout based on the width of the user’s device (the viewport).

There are several other libraries of UI components created specifically for Angular apps. Angular Material offers more than 30 high-quality UI components that follow modern-looking Material Design spec. If 30 components are not enough for your app, use one of the third-party libraries. For example, PrimeNG offers more than 70 UI components for Angular apps. The Flex Layout library supports RWD and we use it together with Angular Material components.

Tooling

The generation of a new Angular project takes less than a minute with Angular CLI, a command line interface that can not only quickly generate a new project, but also generates new components, services, and other artifacts as you continue working on the project. Angular CLI comes with a dev web server with live reload. While your project may consist of hundreds of files, the deployed version of the app will contain a handful of files (not counting images and other resources required by your project.) The size of the deployed and optimized (by Angular CLI) app is small. A Hello World web app weighs under 100Kb, and this includes all the required code from the framework. If your real-world app is modularized, the size of the landing page won’t be more than several hundred KB.

You can debug your TypeScript code right in the browser. Although the browser runs the JavaScript code, the generated source map files allow you to debug TypeScript.

Angular CLI-generated projects also include all configuration files needed for unit and end-to-end testing.

Angular apps on mobile devices

There are two approaches to rendering your app on mobile devices:

  • Keep the same code base, but change the UI layout using responsive web design techniques.
  • Use one of the third party libraries (e.g. Native Script) that offer their own tags to be used in component templates that are converted into the native mobile components.

Server-side rendering

You may want to consider using server-side rendering (SSR) to further improve the speed of rendering of the landing page of your Angular app, which is turned into a plain HTML on the server and looks like a complete app. This is especially useful if the users access your app from mobile devices. Another reason for using SSR is to make your app search engine friendly. Angular Universal is a technology that generates static application pages the server.

Switching to Angular in your organization

What if you already have a number of web apps in production and some of them were written in other frameworks, e.g. AngularJS. What AngularJS and Angular have in common? They have the same seven letters is their names. Other than that, these are different frameworks. If you need to write a new web app – use Angular. If you want to start using Angular in the existing app, but can’t afford a re-write from scratch, you’ll need to write lots of custom code that will introduce Angular into some parts of your code while keeping the rest of the code in whatever framework you’ve been using before. It won’t be easy and will cost you. Check your wallet and think twice before going this route.

SEE ALSO: Angular vs. React – Who’s one step ahead?

So Angular or React?

Any overview of Angular would be not complete unless it includes a comparison with React. You can find lots of articles titled “Why we switched from Angular to React” as well as “Why we switched from React to Angular”. All these comparisons are apples to oranges. Angular is a complete framework with batteries included. It offers fast rendering, routing, dependency injection, rich UI components, server-side rendering, tools for bundling and deployment and more. React is a library for fast rendering UI, and you’d need to pick other libraries for routing, UI components, et al.

For a typical enterprise team of developers with different skill level, I’d recommend using Angular. If any member of your Angular team leaves, you can hire another one who knows Angular and he or she will be productive in no time. If you go with React, your app becomes a meal with a number of a la carte dishes selected by Joe, a senior developer. It’ll take some time for the new hire to get up to speed. If Joe leaves, replacing him is more difficult. If you work for a small startup with a couple of smart developers, selecting a framework is less critical. These 10X developers are productive with any framework, library, or pure JavaScript. Besides, the developer turnover rate in startups is not as high as in enterprises.

If you want to see a trend, check out the StackOverflow data on most dramatic year-over-year increases in technologies. Angular is in the lead. Still, if you’re a decision maker, be very pragmatic in selecting a framework.

This was a very high overview of Angular, but I regularly blog on Angular-related topics and you’re welcome to read these blogs and watch videos here .

This article is part of the “Use, favor, ditch: Angular, Vue.js, React & Node.js”JAX Magazine issue:

If you’re not sure what your list of New Year’s resolutions should include, why not go for JavaScript and its myriad of frameworks and libraries? This JAX Magazine issue should help you decide.

The number of libraries and frameworks could easily overwhelm you so let’s stick to the most popular ones: Angular, React and Vue.js .

您可能感兴趣的

Angular Elements Hi Friends, Hope you are all well. In this post let’s play around with Angular elements. Angular Elements is a new way to write web components ...
Angular 5 To-Do List App In the previous article we learned how to highlight the filter match in a task’s title. The code of the previous article can be found in the ...
Case Study: Patrick Roger’s Headless E-Comme... In this case study, we interview some great folks from Ici La Lune, a French web agency. Joining us are frontend developer and co-founder Benoit P...
Getting started with Angular SDK Angular (v4+) framework is officially out for some time and we recently informed you about releasing Angular SDK to help you create Angular appli...
Get user images twitter | Angular&per... im quite new to angular.js and firebase, so im starting to edit some code from an open source script to expens my knowledge ... i used a chat script w...