我对angular2模板驱动的表单验证有问题,以下是我的表单的代码。
<h1>{{page_title}}</h1>
<div *ngIf="success_flag" class="alert alert-success">
{{success_message.message}}
</div>
<form #add_book_form="ngForm" (ngSubmit)="add_book(add_book_form)" novalidate>
<div class="row">
<div class="col-sm-12 col-md-12 col-lg-12 col-xs-12">
<div class="form-group clearfix">
<label>Book Name</label>
<input name="book_name" id="book_name" [(ngModel)]="book_name" class="form-control" required>
<div *ngIf="book_name.invalid && (book_name.dirty || book_name.touched)" class="alert alert-danger">
<div *ngIf="book_name.errors.required">
Book Name is required.
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12 col-md-12 col-lg-12 col-xs-12">
<div class="form-group clearfix">
<label>Book Description</label>
<textarea name="book_description" [(ngModel)]="book_description" class="form-control" required></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12 col-md-12 col-lg-12 col-xs-12">
<div class="form-group clearfix">
<label>Book Published Date</label>
<input name="book_published_date" [(ngModel)]="book_published_date" class="form-control" required>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12 col-md-12 col-lg-12 col-xs-12">
<div class="form-group clearfix">
<label>Cover Image</label>
<input name="book_cover_image" [(ngModel)]="book_cover_image" class="form-control" type="file" (change)="getFiles($event,'cover_image')" required>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12 col-md-12 col-lg-12 col-xs-12">
<div class="form-group clearfix">
<label>PDF Copy</label>
<input name="book_pdf_copy" [(ngModel)]="book_pdf_copy" class="form-control" type="file" (change)="getFiles($event,'pdf_copy')" required>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12 col-md-12 col-lg-12 col-xs-12">
<div class="form-group clearfix">
<label>PDF Sample</label>
<input name="book_pdf_sample" [(ngModel)]="book_pdf_sample" class="form-control" type="file" (change)="getFiles($event,'pdf_sample')" required>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12 col-md-12 col-lg-12 col-xs-12">
<div class="form-group clearfix">
<label>Price</label>
<input name="book_price" [(ngModel)]="book_price" class="form-control" type="number" required>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12 col-md-12 col-lg-12 col-xs-12">
<div class="form-group clearfix text-center">
<button [disabled]="add_book_form.invalid" class="btn btn-success">Save Book</button>
</div>
</div>
</div>
</form>
目前正在禁用提交按钮。当我尝试填写书名字段时,必须启用它,但它仍然不起作用,我不知道究竟存在哪个问题。错误消息也没有显示出来。
请帮忙。 感谢
答案 0 :(得分:1)
@DBQ是对的。
而不是使用:
<button [disabled]="add_book_form.invalid" class="btn btn-success">Save Book</button>
你应该使用:
<button [disabled]="add_book_form.controls['book_name'].invalid" class="btn btn-success">Save Book</button>