While creating a Model Driven Template Reactive forms, when I create model object from Form Value. Then model object is loosing its TYPE.
For a Simple Example:
You should have an interface and a class, and the class should implement the interface.
Create an empty book with an empty constructor.
export class Book implements IBook {
constructor(public name = '', public isbn = '') {}
}
Create a real model-driven form.
this.bookFormGroup = this.fb.group(new Book());
Correctly type your form
this.newBook: IBook = this.bookFormGroup.value;
you can try this in your addBook()
:
let formData = Object.assign({});
formData = Object.assign(formData, this.bookFormGroup.value);
this.newBook = new Book(formData.name ,formData.isbn );
console.log(this.newBook instanceof Book);
I had this problem and create the formGroup directly to model, solved the problem. In your code:
this.bookFormGroup = this.fb.group(Book);
Book is the class name of your model.
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 safe you a lot of work if the Book class will have any change in future and became bigger.
I have used 'Partical class' to inject value through constractor of class. this can be used when your form calls api and model needed to be passed in without casting or when you create new instance of model from reactive form value.
export class Address {
postCode: string;
line1: string;
line2: string;
county: string;
city: string;
country: string;
cityId: string;
countryId: string;
constructor(initialValues: Partial<Address> = {}) {
if (initialValues) {
for (const key in initialValues) {
if (initialValues.hasOwnProperty(key)) {
this[key] = initialValues[key];
}
}
}
}
}
Change your class definition to
export class Book {
constructor(public name: string, public isbn: string) {}
}
Change your addBook
method to
addBook() {
const { name, isbn } = this.bookFormGroup.value;
this.newBook = new Book(name, isbn);
console.log(this.newBook instanceof Book);
console.log(this.newBook);
}