Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

angular - Reactive Forms correctly convert Form Value to Model Object

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:

Model Class Book:

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

Component:

@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>

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

i.e, After this.newBook = <Book> this.bookFormGroup.value;

this.newBook instanceof Book is becoming FALSE

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

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

question from:https://stackoverflow.com/questions/49997765/reactive-forms-correctly-convert-form-value-to-model-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...