Reputation: 5562
In different projects I have worked on I have seen the following 2 different ways to build reactive forms. Which one is the recommended way?
Using AbstractControl
public form: FormGroup;
public fb: FormBuilder;
public to: AbstractControl;
public subject: AbstractControl;
public body: AbstractControl;
private ngOnInit() {
this.form = this.fb.group({
'to': ['', Validators.compose([Validators.required, emailValidator])],
'subject': ['', Validators.compose([Validators.required])],
'body': ['', Validators.compose([Validators.required])],
});
this.to = this.form.controls['to'];
this.subject = this.form.controls['subject'];
this.body = this.form.controls['body'];
}
Using FormControl
public form: FormGroup;
public fb: FormBuilder;
public to: FormControl;
public subject: FormControl;
public body: FormControl;
private ngOnInit() {
this.form = this.fb.group({
'to': ['', Validators.compose([Validators.required, emailValidator])],
'subject': ['', Validators.compose([Validators.required])],
'body': ['', Validators.compose([Validators.required])],
});
this.to = new FormControl['to'];
this.subject = new FormControl['subject'];
this.body = new FormControl['body'];
}
I also found that the docs here states that AbstractControl should not be instantiated directly, so does that mean method 1 is not the recommended way?
Upvotes: 3
Views: 1961
Reputation: 54
AbstractControl is the base class for most form controls. According to the documentation, you should use the child class -- FormControl -- to instantiate form controls primarily where you get value and validator status for each ui object.
const body = new FormControl({value: 'n/a', disabled: true});
console.log(body.status); // disabled
console.log(body.value); // n/a
Upvotes: 3