The learning content is the MOOCs Angular teaching video

Angular(Typescript) decorators

1.1 introduction

  • A decorator is a function
  • It is a function that returns a function
  • It is not an Angular feature, it is a feature
  • The input arguments to the function are targe, name, and descriptor
  • After this function is executed, it may return a Descriptor object, which is used to configure the target object

1.2 Typescript decorators:

  • Class decorators
  • Property decorators
  • Method decorators
  • Parameter decorators

How to implement a decorator

2.1 Implement an @Emoji() decorator that can make the string passed by a label match

export function Emoji() {
    return (target: Object.key: string) {
        let val = target[key];      
        const getter = () = > {
            return this.val;
        };  
        const setter = () = > {
            val = ` expression${value}Expression `
        };
        Object.defineProperty(target, key, {
            get: getter,
            set: setter,
            enumerable: true.configurable: true}} ## How to use +@Emoji() Result = 'hello'; + {{result}} The page displays: expression Hello expressionCopy the code

2.1 Implement a @confirmable () decorator, popup confirmation dialog box

export function Confirmable(message: string) {
    return (target: Object.key: string.descriptor: PropertyDescriptor) {
        const origin = descriptor.value;
        descriptor.value = function(. args:any) {
            const allow = window.confirm(message);
            if (allow) {
                const result = origin.apply(this, args);
                return result;
            }
            return null;
        };
        
        returndescriptor; }} ## Prefixes the method with this decorator@Confirmable('Are you sure you want to click?')
handlerClick() {
    console.log('click'); } ## a pop-up window will appear before the effect triggers handlerClick, and click ok to continue printing click.Copy the code

Types of Decorators in Angular

  • Reference: presents. Cn/API? Status =…

The following 19 built-in decorators are provided in Angular

Decorator type Built-in decorator
Class decorator 5 @Component, @NgModule, @pipe, @Injectabl, @directive
Property decorator 6 @input, @Output, @contentChild, @contentChildren, @viewChild, @ViewChildren
Method decorator 2 @ HostListener, @ HostBinding
Parameter decorator 6 @attribute, @inject, @optional, @self, @skipself, @host

Iv. Learning content

  • Angular 2 Decorators – Part 1: github.com/semlinker/a…

  • “Presents two Decorators (decorator) – part 2: segmentfault.com/a/119000000…