Angular’s new component structure

With all the new features coming in Angular, the structure of the component (which are the building blocks of an Angular app) is, in my opinion, changing from what it use to be.

Before the introduction of standalone components and Signals, a typical Angular component would be made up of:

  • A TypeScript file
  • A HTML template
  • A CSS/SCSS file

Each part of the component, nicely separated in it’s own file and each component belonging to it’s own module. This approach has worked for many projects and is still used in a lot of Angular projects. It’s great, but things have moved on. More modern web frameworks have taken a slightly different route and the Angular team have worked hard on giving Angular developers the option to write their apps using this new, modern approach.

So from Angular 15+ the Standalone component was introduced, allowing us as Angular developers to create components like this:

import { Component } from '@angular/core';
import { RouterLink } from '@angular/router';

@Component({
  selector: 'app-home-page',
  standalone: true,
  imports: [RouterLink],
  templateUrl: './home-page.component.html',
  styles: ``,
  template: `<h1 class="text-3xl font-bold underline">Hello world!</h1>
    <button
      [routerLink]="['/contact']"
      routerLinkActive="router-link-active"
      class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
    >
      Add User
    </button>`,
})
export class HomePageComponent {}

In this example, we have everything in the single file. The TypeScript code, though not much of it here, the HTML template and a place for the styles. Also any imports are clearly listed in the imports array, everything is just there. Easy to see and read what is happening in this component.

Comparing with Vue

Not only have I worked on Angular projects, I’ve also spent sometime working with VueJS which is a fantastic framework, with a lot of great features and support.

One thing I did like about Vue was it’s approach to single file components, which at the time were not part of Angular. This is how a Vue component looks:

<script setup lang="ts">
import { RouterLink, RouterView } from 'vue-router'
import HelloWorld from './components/HelloWorld.vue'
</script>

<template>
  <header>
    <img alt="Vue logo" class="logo" src="@/assets/logo.svg" width="125" height="125" />

    <div class="wrapper">
      <HelloWorld msg="You did it!" />

      <nav>
        <RouterLink to="/">Home</RouterLink>
        <RouterLink to="/about">About</RouterLink>
      </nav>
    </div>
  </header>

  <RouterView />
</template>

<style scoped>
header {
  line-height: 1.5;
  max-height: 100vh;
}
</style>

Again everything is in the single file and clear to see. I like how in the Vue version the parts of the component are separated into <script>, <template> and <style> sections, making it easier to see the different parts of the component (this is great if your component has a lot of HTML or TypeScript code).

After working with Vue for a bit and enjoying the single file component structure, when I came back to working on an Angular project I missed the simplicity of the SFC (single file component) that Vue uses. But now with SFC components part of the new Angular I think we will start to see more and more Angular projects take advantage of the SFC architecture.

What are the advantages of the SFC approach

As I see it there are a few advantages to the SFC approach that as Angular developers we can now take advantage of, they include:

  • Easier to read code – now with everything in one file it’s easier to get a complete picture of what the component does and how it works. Ideal for when you are taking over an existing project.
  • Easier to maintain – the code for the component is there in one file, changes are easier to keep track of and refactor when in one file rather than jumping between multiple files
  • It’s easier to explain the code base to another developer – going through the code component by component makes it easier to explain how an application works, rather than going through multiple files trying to explain how the app works.
  • It is easier to test – with modules not being such a core part of Angular now, testing and the mocking for tests are more straight forward to write. Removing a lot of the negative reasons why tests are not written. With less to mock it’s easier to write tests and so there is no reason not to write them.

SFC allow cross framework understanding

One of the main advantages I see to SFC’s is it allows developers from other frameworks to pick up Angular easier – before SFC if you showed a React developer or a Vue developer the codebase of an Angular application it can be overwhelming with the amount of files and listing that this TypeScript file belongs with that HTML file. Now a developer with experience of either React or Vue can understand and relate to this new approach in an Angular project. Also the opposite applies, as an Angular developer who has worked with this SFC architecture when I see a Vue or React code base I find it far easier to relate back to what I already know when looking at the code. I think this will mean that as web developers we can work on multiple projects no matter what the framework used, with SFC the architecture is similar in all cases and we all know HTML, CSS and JavaScript which are the building blocks for all web frameworks.

Thinking of converting your Angular app to use SFC

If you, or your company needs help converting your Angular project to using the new SFC architecture feel free to contact me I can help upgrade your Angular apps to use this new architecture.

Update your package.json file for better tests

By default Angular gives you a couple of commands to run:

npm run start
npm run build
npm run watch
npm run test

These commands get you up and running, you can run the app in the browser, build the final version and run tests in run once.

I like to add a few more commands to my package.json file, these extra ones are:

npm run test:watch
npm run test:coverage
npm run test:ci
npm run lint

These commands give me more options for running my tests, in watch mode, with code coverage and in both watch mode with code coverage. There is also a linting check, which is always helpful for code quality checks.

The full commands in package.json look like this:

"test:watch": "ng test --watch",
"test:coverage": "ng test --code-coverage",
"lint": "ng lint",
"test:ci": "ng test --watch=true --browsers=ChromeHeadless --code-coverage"

Out of all four new commands the most essential one is the test:ci one, which runs my tests in headless mode (which is great as I don’t want to have the Karma runner opening the browser all the time) gives me an overview of all the code covered by tests.

While something like NX will give you more options and use Jest, being able to run these commands in a Angular CLI based project does make running tests easier leaving no reason not to write tests.

amazed formal male looking at laptop screen
Angular is exciting again

After finally catching up with the keynote talk at this year’s NgConf and seeing all the new features and direction Angular is moving towards, I really feel that Angular is exciting again.

Not to say it wasn’t exciting before, but when you look at what the other frameworks were doing and the way they allow you to build apps, going back to work on an Angular app wasn’t as exciting as working with something like Vue for example.

It’s not that I don’t enjoy working with Angular, I do, it’s what I specialise in, that’s things did start to appear over complex when you compare it to other approaches and how fast you can develop with them Angular was becoming too over complex and slow to work with.

Why Angular is now a better Choice for building apps

Now, with Angular v16, Angular is back as a great choice to build full-featured applications. I’d actually say that it’s better than other choices as not only can you build Angular apps using a more streamlined approach, but you get all the other features like routing, an HttpClient, a testing framework, the CLI, RxJs all as part of the framework. Removing the need to worry about what third-party library you need to bring into your project just because the framework you’ve chosen doesn’t have built-in support for it.

So what are these new features that make Angular exciting?

In version 16 there are Signals, Standalone Components (which actually came out in version 15), Server-Side Hydration, Required Inputs, and Deferred Loading (this is still in an RFC so might come in a later minor version of v16).

Plus there are a set of new developer experience-related tools that make Angular v16 even better to work with. These tools include schematics to change your NgModule-based applications to use Standalone components, support for TypeScript version 5, the ability to pass data via a route into your components directly using the Component’s inputs instead of just relying on query or path params, an improved Angular language service so imports are automatically added in your editor and so much more. To get a complete overview read this post from the Angular Blog.

Is there a new approach to Angular?

Well, with the new features in v16, Angular apps can now be built using a different approach to previous versions. If you want to build a fast, lightweight application with a few components then previously you may have looked at React or Vue, but now Angular is in that mix because an Angular app can now be developed without large Modules or complete RxJs functions. If you have a team of developers who are new to web development, then having them build an Angular app that just uses components and makes use of Signals to pass data between components (which is conceptually easier to get than RxJs when starting out) is now a great approach.

Angular can now be written in a far more streamlined and straightforward approach, then as the needs of the application grow (and that always happens) more of the features from Angular can be incorporated into the application.

So now you can build Angular apps using a different approach, no more does Angular need to be seen as this web framework where it can only build large-scale enterprise apps can. You want to get started building quickly, use Angular 16, want your team of new developers to learn a well-documented and stable framework, use Angular 16, want to start your new enterprise-level application that needs to be supported over the next 2-5 years, use Angular.

I’m looking forward to diving into Angular 16 over the next few weeks it’s good to be part of the Angular community.

Contractor Chronicles 4

This week I’ve spent working on a very tricky bug, not one that required a complex rewrite to solve, but instead one that was hard to find the cause of.
It was on a Angular app that uses a third party system to generate forms for the application. The issue was that where this third party system had been updated it required a change to one of the forms in the application.

It was tricky to solve due to the fact that it needed a lot of comparing files and lines and lines of JSON to find the issue. Thankfully another developer helped me see the issue and I had been looking at it for hours.

It does go to show that it is always a good idea to get a ‘second pair of eyes’ to look at an issue. There’s no shame in asking for help in the end it helps get the problem solved and the work can continue.

The current contract I have should be ending at the end of April, so I’m going to start looking for the next one soon. Changing contracts is always a interesting time, mainly it’s stressful looking for the next role, but it is also a time to think about maybe trying something different.

If I look around on the job boards and LinkedIn it looks like React is the main choice for building web apps. So when this contract is up it might be time to look at getting into React development.
Having said that, Angular is going through a bit of a change. It now has stand alone components, like React and Vue. It has a new system called Signal coming in the next version, which is a new way of adding Reactivity to your application. These two changes alone mean that Angular apps can soon be written using the same approach as React and Vue, but still have all that Angular provides a complete framework with many of the tools you need for an application (like built in testing, routing, an http client and the CLI).

So is it worth looking at React when Angular could be having a resurgence? I’m not sure. I think at the end this contract I’ll spend a few days building a React app to see what it’s like to work with.

Contractor Chronicles 3

This week was spent working on the maintenance of an existing Angular application, which has been recently updated to Angular 15.

The upgrade was fairly easy, Angular and the Angular CLI make upgrading between versions so easy. It was something I missed when working with Vue. I know that the Vue CLI does have a way of upgrading, but with the Angular CLI being a bit more mature I find the upgrade process far more straightforward.

I also spent a bit of time watching a live Twitch stream of Josh Goldberg (he’s a full-time open-source developer, who specialises in Typescript), in this stream he was reviewing a pull request to a Typescript project Typescript-ESLint, which is a library for adding linting for Typescript to ESLint.

Linting is a way of checking for bad practices in your code, it is a set of rules for JavaScript. This Typescript-ESLint project adds rules for Typescript to ESLint.

As I mentioned in earlier Contractor Chronicles I said I was looking for an open-source Typescript project to get involved in and I started to look more and more into this Typescript ESLint project and get involved in the project.

So this week I spent a bit more time looking at this project and after watching the Twitch Stream of Josh’s I’m starting to understand how the project works and hopefully soon I can start contributing to the project.

Finally, I spent some time going through a plan for the rest of the year, breaking down some goals I have for the years into projects. Then using the PARA method to organise these projects and goals.

assorted books on shelf
Dealing With CommonJS based dependencies

An Angular quick tip I discovered today was if you have an application with many third-party libraries that use CommonJS instead of ES modules. You can add the names of these libraries to the "allowedCommonJsDependencies" option in the builder settings in Angular.json.
This helps remove all the warnings in your build, it is basically telling Angular that these libraries are ok to use CommonJS for now until they are updated.

This is great if you are updating an Angular app, but don’t want to go through and update all the dependencies that are still using the CommonJS approach. Then over time as you update these libraries they can be removed from the "allowedCommonJsDependencies" array.

Here’s a link to the official Angular docs on this – https://angular.io/guide/build#configuring-commonjs-dependencies

Photo by Chris Ried on Unsplash
Using third party libraries are useful as long as they are maintained

There’s no denying that the open-source movement has helped move web development forward. Before open source was so prevalent on the web everything had to be built from scratch, there was no searching on NPM for a library that could help fix an issue you had or a framework to structure your application.
But one of the downsides I see with using third-party libraries in your application is if this library is no longer maintained or updated and your work relies heavily on this library it can easily become a maintenance nightmare.

I’ve worked on a few Angular apps now and many are using third-party libraries every time a new version of Angular is released I have to check if these libraries work with the latest version, which on the whole they do. But if one of these libraries is no longer maintained or worked on, then you are stuck with the choice of either not upgrading your Angular version (something I don’t recommend) or refactoring your code to remove this dependency (something I do recommend).

So when it comes to adding third-party libraries to our codebase we need to make a few decisions. First, is it regularly maintained? Checking the history of the library on GitHub can answer that. If there have been no updates within the last year I get worried. Second, if it is maintained how crucial is this library going to be in my application? If it’s core to how the app works how would I maintain the app if later this library is no longer updated? Will it break my application? Can I easily refactor my code to remove this dependency if I need to? These are all questions that need to be considered before just adding a library.

One tip I have used is if you are using a third-party library or component in your application to wrap it within your own library or component then use this ‘wrapper’ throughout your codebase. So if you need to remove the outdated component/library all you need to do is refactor your ‘wrapper’ to either use another third-party library/component or your own version.

Open source is fantastic, it provides so much but I think that in large-scale applications we need to be defensive in how we use open-source code. Third-party libraries are created by some excellent and hardworking developers, many of whom do this work on top of their own, so I think we should be thankful for their work, but just be aware of how much we are using these libraries.

the word thoughts on a pin board
Further thoughts on using Vue

I’ve been working exclusively with Vue for the past year, and my thoughts on Vue have changed over that time.

When I started using Vue it was when Vue 3 was beginning to be released and there were many changes to how you should build your Vue3 apps. First, you could use both options API and Composition API, which you still can, but the documentation on how to use the new Composition API was still fresh and there were many questions about this new approach. I found myself refactoring a few components in my application from the Options API approach to the Composition API approach, which while fairly straightforward, was a bit of work to do.

Then there was the introduction of the <script setup> approach within the Composition API, this approach now seems to be the preferred way of creating components in Vue 3, but unfortunately, I’ve used the original approach of the Composition API and refactoring again to the script setup approach isn’t something I can justify. I do think that going forward the script setup approach is the way to go and thankfully Vue allows this mix of approaches.

The second major change in Vue has been Vite and the move to this being the preferred approach to building a Vue app over the Vue CLI. You can still use the CLI, but with Vite and the improvements in its speed of it over the CLI, I think that Vite will soon become the default way to start and run a Vue application. Going forward I will use Vite over the CLi for any new Vue applications I create.

The final change I’ve seen since starting to use Vue is the replacement of Vuex with Pinia as the main state management approach within Vue. The application I’ve been working on does use Vuex and has a few Actions, Mutations and Getters from Vuex, which according to the Pinia documentation can be refactored into a Pinia-based approach, but again like the refactoring work needed to convert my Composition API components to using the Script setup approach, this is a large refactoring piece of work that is difficult to justify to my client at this time. Again thankfully Vue 3 still supports using Vuex even though it is no longer being actively updated and should be replaced by Pinia.

Since starting with Vue, the stack I started with and the stack I would use now has gone from Vue 3, Composition API, Vue CLI and Vuex to Vue 2, Composition API (script setup approach) Vite and Pinia.
This to me, seems the ideal approach for building a Vue app.

Now I’ve been working with Vue for the last few months I’m really enjoying working with it and I think I’ll continue working with it, learning more about using it and the best practices for building Vue apps.

Time Boxing

I’ve recently started to use Time Boxing for my work. Time boxing is where you take a task or series of common tasks and work on them for a set time period.

For example, answering emails. Instead of answering them throughout the day, you set a time each day to go through all your emails, read them and respond.

Another example is coding tasks. Instead of trying to get all you coding tasks completed throughout the day, but keep on getting interrupted by other things. You can schedule a time box in your day (from 10am – 2pm) to work on your coding tasks.

Well, the first thing is we need to start grouping tasks together by category and having a way of capturing all these things that arise throughout the day. We all love Todo apps, having one of those where we can quickly capture what we have to do is the first thing.
Then we need to start categorising these tasks we have throughout the day, some examples of these categories are:

  • Emails
  • Coding
  • Meeting
  • Research
  • Planning
  • Admin

As something comes up we capture it in our todo app and give it a category. Next we need to set up our ‘time-boxes’.

In your calendar you need to block out time to work on these categories of tasks. For developers we might say, I have my daily standup at 10am, so from 9-10am I’ll do some Admin tasks, update Jira, add estimates to tickets etc. Then from 10-10:30am I have meetings so that leaves me between 11-3 for coding tasks. So you’ll block out between 11-3 as busy so no meetings can be added to you calendar that time, you switch off Slack and notifications and just focus on your coding tasks. (You do have to plan in breaks within that time, but the main focus between these hours is coding). After those hours you can switch to another time-box, say between 3-4pm you answer emails, slack messages and the final hour of your day is spent doing research/study.

These hours aren’t set, it’s up to you to decide how many time-boxes you have and how long they are. The important thing is to have them set up and in your calendar so you can only work on the related tasks at that time. Using this approach will mean you days are no long scattered, you won’t feel like you’ve achieved nothing in the day, as you have set the time to focus on working on something.

Time boxing can also be used outside work

This approach can also be applied to outside work as well. For example, say you want to learn a musical instrument or write a book. Again you can capture your ideas and the tasks for this. Then set time in you calendar to work solely on that. So every Monday evening between 7-9pm you practice the instrument you are learning or write 1000 work every weekday between 9-10pm.

So far this approach has been working for me, it makes planning your work day easier, without feeling to overwhelmed. I’m going to keep trying to implement this approach over the next few weeks see how it goes.

Working with Vue

For the last few months I’ve been working with VueJS instead of Angular and I’ve honestly been enjoying using a new framework.

The things I like about Vue?

Well, there’s the component-based architecture, which I know other frameworks have, but Vue’s approach is very straightforward. There are now modules, Angular had just released a new version which means you don’t need modules, but I haven’t used it yet to compare. So starting with Vue it was nice to see how another framework handles not using modules.

I really like the Composition API pattern for writing components, it is ideal for creating reusable components and writing reusable code through the concept of composables.

The routing library is very good, similar to Angular’s approach, but with the scope to replace it with another version if one comes out ( so far I’ve only seen one library that is for managing the routing in a Vue app).

There is a great ecosystem built around Vue, with a few people in the community doing some fantastic work around Vue. This means if you want to add a new feature, there might be a library or a composable (I recommend looking at the UseVue site for the list of composables that can be helpful in any project).

A couple of things I’m not too keen on

First one is single file components. I prefer the way Angular handles things with the three separate files. If you have a lot of HTML and CSS in your file, along with the Typescript, I find that I am scrolling up and down the file a lot as I work on it. Now that could be because I’ve put a lot in the component and it could be broken down into smaller components, and I know there is a plug-in for VS Code (Volar) that splits the component across two panels making it easier to work with, but I don’t use VS Code I prefer Webstorm. So single file components are not my favourite feature.

Another thing that I’ve found is, that when I started working on this project we were on the beta of Vue 3, and as I continued developing the project Vue 3 was stabilised. As part of this, some of the preferred approaches were set out by the Vue team. For example, the Pinia state management library is the preferred choice, I’m using Vuex. The script set-up tag is preferred to the setup function in Composition API, but I’ve implemented our components using the setup function approach. Now, these aren’t big issues, but it does mean that our application will need to be refactored one day with these changes to match the preferred way of developing Vue apps. That’s not a major problem, just a pain.

Generally, I like Vue, I think I’d like to use it more. I think with Vue 3 you can build really stable enterprise-level applications without having to buy into a large organisation’s way of working. If you want to build an enterprise application but don’t want to use a product owned by either Google or Facebook, then Vue is the framework for you.

Continuing With Vue

I’m looking forward to continuing with Vue, seeing where it goes and using it more in the future. As an approach for building web applications, it’s extremely good, well thought out and supported. As long as there is a community to support Vue I think it will continue to go from strength to strength.