controllers in modern Angular
A controller plus its template becomes one component. The component owns its template, its styles and its state.
Before · AngularJS
<div ng-controller="UserListCtrl as vm">
<h2>{{ vm.title }}</h2>
</div>
app.controller('UserListCtrl', function (UserService) {
var vm = this;
vm.title = 'Users';
});After · Angular@Component({
selector: 'app-user-list',
template: `<h2>{{ title }}</h2>`,
})
export class UserListComponent {
private users = inject(UserService);
title = 'Users';
}What changes
- ng-controller in the HTML is replaced by the component's selector.
- Dependencies are requested with inject() instead of function parameters.
- Components are standalone: they import what their template uses.
Migration tip. Controllers that do too much are usually the hardest part of a migration. Split them into a component (view logic) and a service (business logic) as you move them.
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