Reactive Forms correctly convert Form Value to Model Object
This constructor will work with any type and will assign any matching filed.
export class Book {
public constructor(init?: Partial<Book>) {
Object.assign(this, init);
}
}
So you will be able to do this:
this.newBook = new Book(this.bookFormGroup.value);
This will save you a lot of work if the Book class will have any change in future and became bigger.
I use spread operator:
this.newBook = {...this.newBook,...this.bookFormGroup.value}
Let's say your model is like this:
export class Content {
ID: number;
Title: string;
Summary: string;
}
Your component will look like this:
export class ContentComponent implements OnInit {
content: Content;
contentForm: FormGroup;
ngOnInit() {
this.contentForm = this.formBuilder.group({
Title: ['', Validators.required],
Summary: ['', Validators.required]
});.....
When the save button is called, you can merge the form builder object and the dto you have:
onContentFormSubmit() {
// stop here if form is invalid
if (this.contentForm.invalid) {
return;
}
this.content = Object.assign(this.content, this.contentForm.value);
}
this.content will have the predefined values you have from onInit and the values from the from group.