BT

New Early adopter or innovator? InfoQ has been working on some new features for you. Learn more

Four Tips for Working with Angular Components

| Posted by Jonathan Saring Follow 0 Followers on Jul 21, 2017. Estimated reading time: 8 minutes |

Key Takeaways

  • Name Your Components Wisely 
  • Use Events Properly
  • Follow the Rule of One
  • Maintain Modularity and Minimize Two-Way Binding
  • Know When to Implement Components

If you want to improve the quality of your applications, you need to improve the quality of your code. That may mean tackling a new concept, or it might simply mean approaching existing concepts in a better and more efficient way. Learning to use components in Angular in the most efficient way possible, for instance, can help you to create applications that are more upgradable, that run more smoothly and that will be more future proof.

Components have been a part of Angular since version .5 of AngularJS and provide a convenient and handy way to organize and recycle code. Angular (the shorthand for Angular 2) is not so much an upgrade to Angular 1.x as much as a ‘sequel’, being entirely rewritten with mobile support and other features in mind. Here, the controllers used in 1.x are completely replaced with components. But whether you use 1.x and are happy sticking with it, whether you’re learning Angular from scratch or whether you’re making the jump: you need to start using components to ensure your code is elegant and futureproof as possible. And whichever category you fall into, you’ll find plenty here that can help streamline the process.

What Are Components?

An Angular component is a simplified directive with an easier configuration that is similar to using Web Components. While new structures and features encourage good coding practice, they do not guarantee it. At the end of the day, this comes down to the wetware: the programmer in question, and arguably, the quality of the coffee.

As with using any type of module or class, it is up to you to make sure you create code that is logical, readable, and reusable and that it will not hog unnecessary resources. In this post, we will take a look at four powerful tips that will help you make better use of angular components.

1. Name Well

A rose by any other name…

You can be the best programmer in the world, but if you don’t have any rhyme or reason behind your naming conventions then you are going to come up short. Of course, this is true for any kind of code, whether we are talking about avoiding arbitrary “magic numbers” (use constants!) or avoiding the temptation to abbreviate variables (what does ‘HRT’ do again?). Naming Angular components is no different. In a perfect world, your components will have names that are highly ‘readable’ and flow like English when inserted into your code. More important is that you can work out what the code actually does when you revisit it months later. Also, wouldn’t it be nice if you could work out what they were called even when you can’t remember?

A common naming convention is to use the feature followed by the type (e.g. feature.type.js). When registering the component name, use camel case so that it reads FeatureType. It’s simple, it’s easy and it logically makes sense. You might choose to go with something else, but all that matters is that it is consistent and has some kind of method behind the madness.

Of course, you should also stick with this same logic when writing the script within the components themselves. All variables should be instantly easy to understand, distinguishable from your command and explained well with comments when necessary. Even if you are creating a personal project and you never intend on sharing it with the world, you should give your components a well-defined public API with logical inputs and outputs.

Likewise, give your components well-defined life cycles and implement lifecycle hooks to give them a sensible structure.

Here’s the thing: all of this takes a little more time and when you are building necessary-but-not-fun components, you may just be in a rush to complete them. Perhaps you are a ‘bigger picture’ kind of programmer and you don’t like sweating the small stuff. Despite that, taking your time to write components well with full names (and comments) will save you a lot of time on the backend. If you are working as part of a team, big or small, this is even more critical.

2. Use Events the Right Way

In keeping with smart naming convention and well-defined API, it’s also important to ensure that your components emit well-named events in order to communicate with other components. Think about what you want to be exposed and this can be a better design choice than using two-way data binding (which we will discuss more in a moment). Use either $emit or $broadcast and remember that sometimes you will be communicating with components that you don’t necessarily know about. Use $rootScope to emit events down the entire component tree. Remember as well though that if another component uses the same event name, this could cause unpredictable bugs.

It’s all about forward planning once again and naming things the right way. If you’re the kind of person who enjoys making spreadsheets and meticulous to-do lists then you’ll probably take to these ideas like a duck to water.

And speaking of events, make sure to familiarize yourself with the lifestyle events that will trigger at certain points during your components’ lifecycles. These include $onInit() which is the first initialization of your component and others like $onChanges and $onDestroy. Keep these events in mind and use it to structure the flow of your components.

3. Don’t Over-Complicate, Remember the Rule of One

With great power comes great responsibility. While the temptation might be to write huge scripts with multiple Angular components, it is much better to follow the ‘rule of one’. In other words, only include one component per file and try to keep said file to <400 lines of code. This makes your code significantly easier to read, navigate and maintain. It prevents collisions when using source-control options such as Git and it prevents issues with repeated variables and the like.

Apart from anything else, make an effort to maintain modularity. That way, you ensure you are able to quickly grab and reuse your components as you need them in future projects. In the same spirit, try to create modules that represent feature areas and build one application root module that will pull everything together and create the necessary flow.

Again, this is why it pays to have well named components with useful public APIs. Think of your application as a tree of components. Each one implements clearly defined inputs and outputs with minimal two-way data binding.

This will also make your code much easier to visualize and to think about. Rather than trying to follow a huge amount of spaghetti code, you can build upon your functionality, make tweaks or streamline simply by inspecting how each individual component is working. A word of caution: structuring your code this well can increase the temptation for feature bloat. When it is so easy to add new functionality to your web app, why not go for it? Just keep in mind, simplicity is beneficial at every level of your program. It’s usually better to focus on doing one thing and doing that one thing exceedingly well with simple, reusable code underpinning it all.

4 Know When to Use Components

Finally, make sure that you know when to use components. Components are simpler than using directives and thus they encourage the simple, lightweight code. For those using AngularJS, their use also makes the change to Angular that much easier and optimizes your code for component-based architecture. If you have not adopted Angular components into your workflow yet, then it’s time to get with the program (literally and metaphorically).

Likewise, recognize the limitations of components. They are not suitable for directives that need to perform actions in compile and pre-link functions - these are not available. Also, they can’t access advanced directive definition options (priority, terminal etc.) and you should stick with the directive method when you want it to be triggered by a CSS class or attribute instead of an element.

Components can and should also be organized and reused. You can group components together into collective libraries much like Material2 and others, or publish them as separate packages (which might not always be that simple). You can also use an open source component repository to create your own arsenal of reusable components without the configuration overhead of packages. This will allow you to organize components together while being able to find, modify and use them individually. The right work methodology can help achieve better modularity, management and reuse of Angular components across applications.

Other than habit and resistance to change, this is another reason that some developers might find themselves still relying on .directive(). Some coders will simply prefer to choose the methods that they can use throughout their code in order to keep things simple. But using components saves a lot of boilerplate and the rarity of non-component directives actually helps them to stand out. So, in short, make sure that you are using components, and more importantly, that you are using them well

Conclusion

To a large extent, using Angular components well simply means employing the best general coding practices. Name smartly, think about your team and future iterations and keep things simple. It’s all about restraint and finesse. If you do keep this in mind and make the leap to components, your code should be elegant and effective.

About the Author

Jonathan Saring is a tech lover and startup guy by day, open-source addict by night. Believes in the power of technology and community coming together. Part of the great Bit team building Lego-like code.

Rate this Article

Adoption Stage
Style

Hello stranger!

You need to Register an InfoQ account or or login to post comments. But there's so much more behind being registered.

Get the most out of the InfoQ experience.

Tell us what you think

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

Working patterns and code-styles from AngularJS don't necensarry apply to Angular(2+). by Lukas Prömer

Your article seems to target both, AngularJS and Angular developer. Thought the specific points you make in your blogpost seem to refer only to AngularJS.

As Example:
Other then in AngularJS, working with Events is not recommended in Angular. Instead you create a service wich provides an Observable.

AngularJS was originally not Designed for the work it was used for. If you plan to make a new project I recommend using Angular(2+). Because the codestyle is more well definied and because it provides a much better performance.
For that matter I also recommend using Angular CLI. It will help a lot with your general code-structure.

Lg Lukas
P.s. Sorry if my English sounds disturbing. Its not my native tongue.

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

1 Discuss

Login to InfoQ to interact with what matters most to you.


Recover your password...

Follow

Follow your favorite topics and editors

Quick overview of most important highlights in the industry and on the site.

Like

More signal, less noise

Build your own feed by choosing topics you want to read about and editors you want to hear from.

Notifications

Stay up-to-date

Set up your notifications and don't miss out on content that matters to you

BT