I'm following a bit outdated tutorial as an intro to Angular (https://www.udemy.com/course/angular-for-beginners-course/learn/lecture/12538306#overview). It is using some older Angular version. I'm a total noob in Angular.
Upon creating a custom component, in the that older version of Angular that the course is using, there is a constructor() and ngOnInit(), that are not present in Angular 14. Are they deprecated or somehow used elsewhere, or simply not generated by Angular CLI automatically anymore? What is the reason for this difference in the generated component code?
Here the code: (Angular 14)
import { Component } from '@angular/core';
@Component({
selector: 'course-card',
templateUrl: './course-card.component.html',
styleUrls: ['./course-card.component.css']
})
export class CourseCardComponent {
}
(older version)
import { Component } from '@angular/core';
@Component({
selector: 'course-card',
templateUrl: './course-card.component.html',
styleUrls: ['./course-card.component.css']
})
export class CourseCardComponent implements OnInit {
constructor() { }
ngOnInit() { }
}
constructor
is a part of Typescript, and ngOnInit()
is still valid component lifecycle hook.
Neither of those are mandatory (now and in older versions of angular) in order for componen
t to work and some lint
configurations (maybe even the default one provided with the skeleton app) yelds an error for empty method definitions.
I guess this is the reason (both beeing non mandatory).
The constructor
and ngOnInit
were removed from generated component, because Angular programmers (including myself) preferred to add these only when needed. They are not deprecated.
See the pull request removing it.
As time goes by , angular versions get updated and so components generated no longer have constructor and ngOnInit in the newer versions of Angular. I suspect this was done to crunch down on boilerplate code seeing as you only need to use them when you are doing dependency injection and lifecycle hooking. Other than that, they are not deprecated at all.
I tested with Angular CLI: 14.2.0 ng version | ng v
and upon executing ng g c test
to generate a componenet named test the output has expected with constructor
and ngOnInit()
:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}
As of Angular CLI 15+ ng generate component
no longer includes constructor
and ngOnInit()
in the default generation output.
Do note that I am talking about Angular CLI, not Angular project version.