Reputation: 2383
I have been learning to use reactive forms in angular 7 but have some trouble understanding how to use it.
Example:
Export class Person {
id: string,
name: string
}
Export class myFormComponent implememts OnInit {
personForm: FormGroup;
@Input()
person: Person;
Constructor(private fb: FormBuilder) {}
NgOnInit() {
this.personForm = this.fb.group({
name: [this.person.name, [Validators.required]]
});
}
}
<form [formGroup]="personForm" >
<input formControlName="name" >
</form>
My component takes in entry a person object to edit, but seeing as we are not using ([ngModel])
the values are not modified inside the person model that is passed in the parameters of the component.
Now I know we can just read the values of the form on submit and affect the changes to the properties one by one or by affecting all form values but that would mean we are missing the id attribute (as we don't use it in the form).
I just want to know what the best practice is in this type of scenario.
Upvotes: 0
Views: 4314
Reputation:
The principles of reactive forms and template driven forms are very different : you can't really compare them and expect the same things from both.
In the documentation, under "Key differences", you will see that they both have very different purposes.
To sum it up, template driven updates the model in a direct way, while reactive forms copy the model and updates the copy of the model.
If you want to update your model with reactive forms, you do it on demand (for instance, right before making an HTTP call).
They both have their advantages and drawbacks, and you should use them accordingly. They're complementary, not competing.
Upvotes: 2