Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are constrctor() and ngOnInit() not added to the component code in Angular 14?

Tags:

angular

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() { }
}
like image 626
Dominika Wojewska Avatar asked Oct 29 '25 01:10

Dominika Wojewska


1 Answers

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:

https://blog.ninja-squad.com/2022/11/16/angular-cli-15.0/

https://indepth.dev/posts/1508/structure-initialization-logic-without-ngoninit-utilize-observables-and-ngonchanges

like image 132
Joosep Parts Avatar answered Oct 30 '25 17:10

Joosep Parts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!