最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is using FormBuilder in the constructor a bad practice? - Stack Overflow

programmeradmin4浏览0评论

Angular doc here you can see below kind of implementation.i.e declare formBuilder and services inside the constructor(). I know use services inside the constructor() is a bad practice. i.e. we need to use ngOnInit() for that. But I also use constructor() for declaring formBuilder properties. Is that too bad practice? Do I need to use ngOnInit() for that too? Will page creation holds until formBuilder creation?

export class CartComponent {
  items;
  checkoutForm;

  constructor(
    private cartService: CartService,
    private formBuilder: FormBuilder,
  ) {
    this.items = this.cartService.getItems();

    this.checkoutForm = this.formBuilder.group({
      name: '',
      address: ''
    });
  }
}

Angular doc here you can see below kind of implementation.i.e declare formBuilder and services inside the constructor(). I know use services inside the constructor() is a bad practice. i.e. we need to use ngOnInit() for that. But I also use constructor() for declaring formBuilder properties. Is that too bad practice? Do I need to use ngOnInit() for that too? Will page creation holds until formBuilder creation?

export class CartComponent {
  items;
  checkoutForm;

  constructor(
    private cartService: CartService,
    private formBuilder: FormBuilder,
  ) {
    this.items = this.cartService.getItems();

    this.checkoutForm = this.formBuilder.group({
      name: '',
      address: ''
    });
  }
}
Share Improve this question edited Oct 20, 2019 at 13:58 Tsvetan Ganev 8,8764 gold badges31 silver badges45 bronze badges asked Oct 20, 2019 at 13:57 SampathSampath 66k70 gold badges325 silver badges459 bronze badges 1
  • ngOnInit() would be the most appropriate place for that too. Will page creation holds until formBuilder creation? -- Yes, but in your case that wait is negligible. – Nicholas K Commented Oct 20, 2019 at 14:00
Add a ment  | 

2 Answers 2

Reset to default 6

Short answer, yes, you should leave most of the initialisation logic within the ngOnInit lifecycle hook.

According to the angular docs for OnInit, it is used to

  • To perform plex initializations shortly after construction.
  • To set up the ponent after Angular sets the input properties.

Therefore, it will be cleaner to carry out logic such as fetching of data, and initialisation of your formbuilders on your ngOnInit lifeycle hook.

You should check out this post by Misko Hevery, who is the team lead for Angular, who has outlined a number of reasons to keep the constructor clean.

Injecting FormBuilder in the Constructor

Injecting FormBuilder in the constructor is the remended best practice, since Angular uses the constructor injection pattern.

Using FormBuilder in the Constructor

Whether or not to initialize the reactive form in the constructor or the ngOnInit lifecycle hook is largely a matter of preference. But in the interest of keeping code tidy, refactoring initialization logic into ngOnInit (or other methods) is a good idea.

Regarding the timing of ngOnInit, the docs state:

[ngOnInit is a] callback method that is invoked immediately after the default change detector has checked the directive's data-bound properties for the first time, and before any of the view or content children have been checked. It is invoked only once when the directive is instantiated.

Hence, initializing a form in ngOnInit will take place prior to the page view being loaded.


The official Angular docs for Reactive Forms initialize the form as follows:

@Component({
  selector: 'app-profile-editor',
  templateUrl: './profile-editor.ponent.html',
  styleUrls: ['./profile-editor.ponent.css']
})
export class ProfileEditorComponent {
  profileForm = this.fb.group({
    firstName: ['', Validators.required],
    lastName: [''],
    address: this.fb.group({
      street: [''],
      city: [''],
      state: [''],
      zip: ['']
    }),
    aliases: this.fb.array([
      this.fb.control('')
    ])
  });

  get aliases() {
    return this.profileForm.get('aliases') as FormArray;
  }

  constructor(private fb: FormBuilder) { }
}

See Angular Stackblitz Demo

发布评论

评论列表(0)

  1. 暂无评论