Carlos Cifuentes
AngularJS → Angular reference

$onInit / $onChanges / $onDestroy / $postLink in modern Angular

The AngularJS component hooks have direct successors: ngOnInit, ngOnChanges and ngOnDestroy. With signal inputs, most of that code moves to computed, effect and DestroyRef.

Before · AngularJS
app.component('userChart', {
  bindings: { userId: '<' },
  controller: function ($element, ChartService) {
    var ctrl = this, chart;
    ctrl.$onInit = function () { ctrl.ready = true; };
    ctrl.$onChanges = function (changes) {
      if (changes.userId) { ctrl.load(changes.userId.currentValue); }
    };
    ctrl.$postLink = function () { chart = ChartService.create($element[0]); };
    ctrl.$onDestroy = function () { chart.destroy(); };
  }
});
After · Angular
export class UserChartComponent {
  private host = inject<ElementRef<HTMLElement>>(ElementRef);
  private charts = inject(ChartService);
  private destroyRef = inject(DestroyRef);
  userId = input.required<string>();

  constructor() {
    effect(() => this.load(this.userId()));               // $onChanges
    afterNextRender(() => {                                // $postLink
      const chart = this.charts.create(this.host.nativeElement);
      this.destroyRef.onDestroy(() => chart.destroy());   // $onDestroy
    });
  }

  private load(id: string) { /* request the chart data */ }
}

What changes

  • $onInit becomes ngOnInit, or plain field initializers when the code does not read an input.
  • $onChanges becomes computed or effect over signal inputs; ngOnChanges with SimpleChanges still works for decorator inputs.
  • $postLink becomes afterNextRender, which runs once in the browser after the component is rendered; $onDestroy becomes ngOnDestroy or DestroyRef.onDestroy.

Migration tip. Most $onChanges bodies only recalculate a value from a binding. Convert those to computed first, and keep effect for the few that start a request or touch the DOM.

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