反应性表单正确将表单值转换为模型对象 [英] Reactive Forms correctly convert Form Value to Model Object

查看:81
本文介绍了反应性表单正确将表单值转换为模型对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我从表单值"创建模型对象时,在创建模型驱动的模板反应性"表单时.然后,模型对象将失去其TYPE.

While creating a Model Driven Template Reactive forms, when I create model object from Form Value. Then model object is loosing its TYPE.

举一个简单的例子:

模型课本:

export class Book {
  public name: string;
  public isbn: string;
}

组件:

@Component({
  selector: 'app-book',
  templateUrl: './book.component.html',
  styleUrls: ['./book.component.css']
})
export class BookComponent implements OnInit {

  bookFormGroup: FormGroup;
  private newBook: Book = new Book();

  constructor(private fb: FormBuilder) {
    this.bookFormGroup = this.fb.group({
      name: new FormControl(''),
      isbn: new FormControl('')
    });
  }

  ngOnInit() {
  }

  addBook() {
    console.log('submit');
    this.newBook = <Book> this.bookFormGroup.value;
    console.log(this.newBook instanceof Book);
    console.log(this.newBook);
  }

}

HTML:

<form [formGroup]="bookFormGroup" (ngSubmit)="addBook()">
    <input type="text" formControlName="name" >
    <input type="text" formControlName="isbn" >

    <input type="submit" value="Submit">
</form>

在上面的示例中,填充newBook实例后,其转换为普通的Object

In the above example, after filling newBook instance its converted to normal Object

即 在this.newBook = <Book> this.bookFormGroup.value;

this.newBook instanceof Book变为FALSE

如何防止这种情况? 还是有更好的方法来实现这一目标?

How do I prevent this? Or is there any better way to achieve this?

注意:我尝试使用JSON.parse(),但仍然相同.

Note: I tried with JSON.parse() but it still same.

推荐答案

此构造函数可使用任何类型,并将分配任何匹配的文件.

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);

如果Book类将来有任何变化并变得更大,这将为您带来很多工作上的安全.

This will safe you a lot of work if the Book class will have any change in future and became bigger.

这篇关于反应性表单正确将表单值转换为模型对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆