How to mark a component selector as deprecated?

Probably you can write something like this inside your component code:

import { Component, ElementRef } from '@angular/core'

@Component({
 selector: 'app-new-selector,app-old-selector',
 templateUrl: './component.html'
})
export class YourComponent {
    constructor(elem: ElementRef) {
        const tagName = elem.nativeElement.tagName.toLowerCase();
        if (tagName === 'app-old-selector') {
           console.warn('message');
        }
    }
}

It means that we simply compare the tag name of currently started component with the string representing deprecated value. If they are equal - it means that you now need to inform developer.

Here is a working Stackblitz example. Feel free to run it with console opened.


I have written a reusable decorator which marks components' selectors as deprecated.

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

type Constructor<T = {}> = new (...args: any[]) => T;

export function Deprecated(oldSelector: string) { // This is a decorator factory
  return <T extends Constructor>(Base: T) => {
    return class Deprecated extends Base {
      selectors = [];
      constructor(...args: any[]) {
         super(...args);
         const selector = new Component((Deprecated as any).__annotations__[0]).selector;
         this.selectors = selector.split(', ');
         this.selectors = this.selectors.filter(selector => selector !== oldSelector);
         console.warn('The selector "' + oldSelector + '" is going to be deprecated. Please use one of these selectors [ ' + this.selectors.toString() + ' ]');
      }
    };
  };
}

Now we just have to decorate our component class with this decorator function with parameter like below

@Component({
  selector: 'my-old-app, my-app-new',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
@Deprecated("my-old-app")
export class AppComponent  {
  name = 'Angular';
}

Please find the code here at stackblitz.

Also, please read my blog on the same topic which has the explanation on the logic.