Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

500
Visualizações
Why should I create my Angular2 reactive form in the constructor instead of ngOnInit?

As indicated in other responses, the initial routines of an Angular2 application should be launched in the ngOnInit() method, leaving the constructor specifically for dependency injection.

However, in the Reactive Forms tutorial that I'm following, the initialization of the form is in the constructor:

export class HeroDetailComponent3 {
  heroForm: FormGroup; // <--- heroForm is of type FormGroup

  constructor(private fb: FormBuilder) { // <--- inject FormBuilder
    this.createForm();
  }

  createForm() {
    this.heroForm = this.fb.group({
      name: '', // <--- the FormControl called "name"
    });
  }
}

Is there really a significant difference or is it just a minor issue?

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Initializing the formGroup in ngOnInit() is not a bad practice, as it will actually be required if you want your form to be initialized with values that depend (directly or indirectly) from your component @Input()s.

For instance:

class SignInFormComponent {
  @Input() currentLogin: string;
  formGroup: FormGroup;

  constructor(private fb: FormBuilder) {
    // this.currentLogin is not known yet here
  }

  ngOnInit(): void {
    this.formGroup = this.fb.group({
      loginEmail: [this.currentLogin, Validators.email],
      loginPassword: [''],
    });
  }
}
about 4 years ago · Santiago Trujillo Relatório

0

Depends upon your specific use case and design. Possibly you will run into issues relating to get methods on which some of your other formControls might depend on. You might benefit from creating your form inside the constructor and your form will be ready as soon as the component is rendered. However, if you need to do subscribe to .valueChanges on the form for some formControls, you might have a timing issue. You cannot build your dependent formControls unless you .subscribe, and you cannot .subscribe until the form is initialized. You might encounter error: cannot read property 'get' of undefined.

about 4 years ago · Santiago Trujillo Relatório

0

I belive it because of the createForm method in constructor will execute before ngOninit and your form will be ready for use as soon your component is rendered.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda