Carlos Cifuentes
AngularJS → Angular reference

directives in modern Angular

Element directives with a template become components. Attribute directives stay directives, written as classes.

Before · AngularJS
app.directive('autofocus', function () {
  return {
    restrict: 'A',
    link: function (scope, element) { element[0].focus(); }
  };
});
After · Angular
@Directive({ selector: '[appAutofocus]' })
export class AutofocusDirective {
  private el = inject<ElementRef<HTMLElement>>(ElementRef);

  constructor() {
    afterNextRender(() => this.el.nativeElement.focus());
  }
}

What changes

  • restrict: 'E' with a template becomes a @Component.
  • restrict: 'A' becomes a @Directive with an attribute selector.
  • The link function becomes class code, lifecycle hooks and host bindings.

Migration tip. Directives that wrap jQuery plugins need a decision each: wrap the plugin again, or replace it with a native Angular component.

Related

Planning a migration or a micro-frontend platform?

In a 20-minute call you describe your situation and I tell you how I'd approach it. If it isn't worth doing yet, I'll say so.

Message me on LinkedIn