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() { }
}
CodePudding user response:
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.
CodePudding user response:
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).
CodePudding user response:
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.
CodePudding user response:
With Angular CLI: 14 ng version | ng v
upon executing ng g c test
to generate a component named "test" the output has expected constructor
and ngOnInit()
.
As of Angular CLI 15 ng g c test
no longer includes constructor
and ngOnInit()
in the default generation output.
Whether this change is good or bad, time will tell. To generate constructor
and ngOnInit()
with components you'd have to modify schematics or downgrade to Angular CLI 14.
Here's the recap: