我正在尝试在模式之间绑定数据,其内容是用于编辑数据的表单。我正在使用ng-model指令,但组件中的对象不与数据绑定。 我想绑定表单的数据,然后创建一个表示表单数据的对象的实例,以便提交它。
成分:
import { Component, OnInit, TemplateRef } from '@angular/core';
import { BookInterface } from './book';
import { BookService } from './book.service';
import { BsModalService } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/modal-options.class';
import { BookClass } from './book-class';
@Component({
moduleId: module.id,
templateUrl: 'books-list.component.html',
styleUrls: ['books-list.component.css']
})
export class BookListComponent implements OnInit {
pageTitle: string = 'Book List';
imageWidth: number = 100;
imageMargin: number = 2;
listFilter: string;
errorMessage: string;
book = new BookClass(0, "", "", new Date("February 4, 2016 10:13:00"), "");
books: BookInterface[];
public modalRef: BsModalRef;
constructor(private _bookService: BookService, private modalService:
BsModalService) {
}
ngOnInit(): void {
this._bookService.getBooks()
.subscribe(books => this.books = books,
error => this.errorMessage = <any>error);
}
public openModal(template: TemplateRef<any>) {
this.modalRef = this.modalService.show(template);
}
onSubmit(): void {
this._bookService.editBook(this.book);
}
// TODO: Remove this when we're done
get diagnostic() { return JSON.stringify(this.book); }
}
模态:
<ng-template #template>
<div class="modal-header">
<h4 class="modal-title pull-left">Modal</h4>
<button type="button" class="close pull-right" aria-label="Close" (click)="modalRef.hide()">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<h1>Book Edit</h1>
{{diagnostic}}
<form (ngSubmit)="onSubmit()" #bookForm="ngForm">
<div class="form-group">
<input type="hidden" class="form-control" id="bookId" name="bookId" [(ngModel)]="book.bookId">
</div>
<div class="form-group">
<input type="hidden" class="form-control" id="imageUrl" name="imageUrl" [(ngModel)]="book.imageUrl">
</div>
<div class="form-group">
<label for="title">Book Title</label>
<input type="text" class="form-control" id="bookTitle" name="bookTitle" [(ngModel)]="book.bookTitle" #bookT="ngModel" required>
<div *ngIf="bookT.invalid" class="alert alert-danger">
<div *ngIf="bookT.errors.required">
Book Title is required.
</div>
</div>
</div>
</form>
</div>
</ng-template>
答案 0 :(得分:0)
为了将所有表单控件值绑定到表单对象,即bookForm,您必须为每个表单控件使用formControlName或name属性。如果使用NgModel,则对象无法绑定到模型。
<input type="hidden" class="form-control" id="bookId" name="bookId">
在表单提交方法onSubmit()中访问表单时,可以这样做:
this.form.value
表单对象的JSON结构将是:
this.form.value => { bookId: '#a213", imageUrl: 'http://www.example.com/a1', bookTitle: 'A Song of Ice and Fire'}
然后您可以通过POST请求进行字符串化和发送。