2

On an Angular 12 componente I have the following:


export class SignUpComponent implements OnInit {

  environment: Environment;
  form: FormGroup;
  stage: number;

  constructor(
    private router: Router, 
    private title: Title, 
    private formBuilder: FormBuilder, 
    private analyticsService: AnalyticsService, 
    private environmentService: EnvironmentService) { 

    this.environment = this.environmentService.get();

    this.title.setTitle('Registar - Bons Alunos');

    this.analyticsService.pageview('Sign Up', this.router.url);

    this.form = this.formBuilder.group({ 
      email: ['', [Validators.required, Validators.email]]
    });

    this.stage = 1;

  }

  ngOnInit() { }

Question

What should I move from the component's constructor to the ngOnInit method?

What kind of code should I place on ngOnInit that cannot / should not be on the constructor?

JSON Derulo
  • 9,780
  • 7
  • 39
  • 56
Miguel Moura
  • 36,732
  • 85
  • 259
  • 481
  • Angular team, even moves the form initialization before the constructor method, as you can see here: https://angular.io/guide/reactive-forms#using-the-formbuilder-service-to-generate-controls – Juan Vicente Berzosa Tejero Aug 28 '21 at 16:42
  • I’ve read that question before and is still not very clear that is why in my question I added different items in constructor code to try understand which ones should be moved to ngOnInit. For example, setting the title, defining something that depends on route or a variable declaration – Miguel Moura Aug 28 '21 at 16:43
  • @JuanBerzosaTejero Isn't the same thing, I mean, initializing the variables before the constructor or inside the constructor? – Miguel Moura Aug 28 '21 at 17:20
  • Maybe, it depends on how you see it... Anyway, it's not important, it was just a thing that drew me attention when I learned forms. – Juan Vicente Berzosa Tejero Aug 28 '21 at 17:43
  • Constructor is called when the class is instantiated and ngOnint is called just after Constructor. We can use initialization or declaration in both method. But to avoid stuff in Constructor we use ngOnInit. ngOnInit is not mandatory but use this is a good practice. constructor() to setup Dependency Injection, initialization/declaration. If you have some logic to write then use them in ngOnInit() instead writing in Constructor you can use ngOnit. In your case you have used service in Constructor that should be in Constructor only you can place this.stage=1; in ngOnIt(). – Rajesh Kumar Swain Aug 28 '21 at 18:34

0 Answers0