Class and property decorators

Decorators can be used as wrappers around code, such as classes, functions, or even properties, as well as getters and setters. They are used to add an additional feature to that piece of code. 

The Angular team wanted to use decorators in JavaScript—in fact, the Angular team first proposed this by creating a superset of TypeScript called AtScript, which was later merged into TypeScript. Decorators have been proposed as a feature for future JavaScript. The following code shows examples of class and property decorators:

@Component({
selector: 'app-cars',
templateUrl: './cars.component.html',
styleUrl: './cars.component.css'
})
class CarsComponent {
@Input() cars: ICar[]; // Array of ICar type
// property sameMake takes type boolean explicitly here because of
the assignment
private sameMake = true;

/*
Function updateCarYear takes parameter car of type ICar,
and doesn't returns anything(void)
*/
public updateCarYear(car: ICar): void {
car.year = car.year + 1;
}
}

In this example, we are using a couple of decorators: @Component and @Input. @Component is a class decorator that's defined by Angular which takes the configuration of the component as an object, whereas @Input is a property decorator that makes the cars property the input for the component.

We see how these simple decorators can add a lot of capabilities to the classes or class properties. Next, let's learn about access modifiers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset