Reactive Forms correctly convert Form Value to Model Object

后端 未结 8 1013
刺人心
刺人心 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:53

    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.

提交回复
热议问题