简体   繁体   中英

What is best practice for component with reactive forms?

I am struggling to determine what the best practice is for defining components that use reactive forms.

For example, the Reactive Forms docs give an example like:

1)

export class HeroDetailComponent2 {
  heroForm = new FormGroup ({
    name: new FormControl()
  });
}

and

2)

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"
     });
   }
}

The problem with 1 , obviously, is that we don't have access to properties of the component so we can set the initial values. The better approach we see is in option 2 .

However I have also read in the docs (can't find the link at this moment) that one should avoid putting logic inside constructor of components, instead we should favour ngOnInit(), because it makes testing easier and more performant.

I follow this practice of putting component initialisation logic in ngOnInit() pretty much where ever possible. However, I bump in to a problem when I have a component that references the formGroup property.

The problem occurs because the view is being rendered before ngOnInit executes and therefore my form group is not instantiated at that point. One way to work around it is using *ngIf in various place - but that seems messy to me.

So my question:

Is it wise to ignore this suggestion of not putting logic in the constructor in favour of ngOnInit for these cases? Baring in mind that in some cases I may have some calculations to make before I can make my formGroup instance?

I cannot seem to find a alternative life cycle hook that would suit? is there another way?

I will suggest you use angular life cycle hooks and create reactive forms on ngOnInit()

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

   constructor(private fb: FormBuilder) { // <--- inject FormBuilder

   }

   ngOnInit(){
      this.createForm();
   }

   createForm() {
     this.heroForm = this.fb.group({
       name: new FormControl('', [Validators.required])
     });
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM