ng-init in modern Angular
ng-init disappears. Initial state belongs in the component class, and template aliases use @let.
Before · AngularJS
<div ng-controller="ReportCtrl as vm"
ng-init="vm.load(2024); vm.tab = 'summary'">
<div ng-repeat="row in vm.rows" ng-init="rowTotal = row.qty * row.price">
{{ rowTotal }}
</div>
</div>After · Angularexport class ReportComponent implements OnInit {
year = input(2024);
tab = signal<'summary' | 'detail'>('summary');
rows = signal<Row[]>([]);
ngOnInit() {
this.load(this.year());
}
}
<!-- template -->
@for (row of rows(); track row.id) {
@let rowTotal = row.qty * row.price;
<div>{{ rowTotal }}</div>
}What changes
- Initial values become field initializers; calls that load data go in the constructor, or in ngOnInit when they depend on inputs.
- Aliases created with ng-init inside ng-repeat become @let declarations (Angular 18.1 and later) or computed signals.
- Values that the server wrote into ng-init need another channel, such as an API call or a JSON script tag read at startup.
Migration tip. Search for ng-init in server-rendered pages (JSP, Razor, ERB, Blade). That is where the backend passes data to the frontend, and that coupling has to be replaced before the screen can move.
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