As frontend developers we love beautiful UI. In the same vein, we really should strive to have clean reusable code. Modern tools and techniques provide us with many ways to achieve that. In this article, we will look at typescript decorators, and how they can help us add abstraction and reusability to our code.

We will do that by creating a custom decorator to launch a  Sweetalert.

But first of all let us look at what decorators are.

When I was first introduced to decorators, I wondered why we needed them at all. I mean sure, Angular uses that @Whatever symbols everywhere but how did they actually work? Ultimately they looked like black boxes. And surely, one can build apps in TS / Angular without understanding them. But once we dig a little deeper we can understand what they are, as well as the benefits of using them.

What are decorators?

At its core, a decorator is just a JavaScript function. Ok i know this sounds like a joke but really! A decorator is just a function that allows us to “extend” our code to do more. Yes it’s very abstract for now but we’ll get to clarify that soon.

Let’s look at the different types of decorators available in typescript.

There are four main types:

  • Class decorators, which are used to add functionality to a class e.g. @Component and @NgModule
  • Property decorators for adding functionality to properties inside classes, e.g. @Input and @Output
  • Method decorators for methods inside classes, e.g. @HostListener
  • Parameter decorators for parameters inside class constructors, e.g. @Inject

Each decorator has a unique role. For examples of the different decorator types and their application in angular, please check  Decorators used in Angular.

Those are the basics you should know before we can jump into the fun part, actual code :) As mentioned earlier, we will be creating a method decorator that will show a sweetalert confirmation box before a method is executed.

#custom #confirmable #angular #decorators #typescript

Building Custom Typescript Decorators for Angular
3.15 GEEK