Reactive Forms correctly convert Form Value to Model Object

后端 未结 8 1008
刺人心
刺人心 2020-12-04 18:29

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:

相关标签:
8条回答
  • 2020-12-04 18:35
    1. You should have an interface and a class, and the class should implement the interface.

    2. Create an empty book with an empty constructor.

      export class Book implements IBook {
        constructor(public name = '', public isbn = '') {}
      }
      
    3. Create a real model-driven form.

      this.bookFormGroup = this.fb.group(new Book());
      
    4. Correctly type your form

      this.newBook: IBook = this.bookFormGroup.value;
      
    0 讨论(0)
  • 2020-12-04 18:35

    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);
    
    0 讨论(0)
  • 2020-12-04 18:35

    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.

    0 讨论(0)
  • 2020-12-04 18:42

    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.

    0 讨论(0)
  • 2020-12-04 18:43

    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];
            }
          }
        }
      }
    }
    
    0 讨论(0)
  • 2020-12-04 18:52

    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);
    }
    
    0 讨论(0)
提交回复
热议问题