1、安装模块:
cnpm install ng2-validation --save
2、配置module.ts 在自己的模块module下面引入
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import {CustomFormsModule} from "ng2-validation";
...
imports: [
FormsModule,
CustomFormsModule,
ReactiveFormsModule
],
...
3、具体使用
<div class="form-group">
<label class="col-sm-4 control-label">课程:</label>
<div class="col-sm-8">
<select class="form-control" [(ngModel)]="onClassInfo.courseId" id="courseId" name="courseId" required #courseId="ngModel">
<option *ngFor="let option of courseNameOptions" [value]="option?.id">{{option?.courseName}}</option>
</select>
<p class="text-danger" [hidden]="courseId.valid||courseId.pristine">课程不能为空</p>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label">学年学期:</label>
<div class="col-sm-8">
<select class="form-control" id="semesterId" [(ngModel)]="onClassInfo.semesterId" name="semesterId" #semesterId="ngModel" required >
<option *ngFor="let option of yearTermOptions" [value]="option?.id">{{option?.dictionaryName}}</option>
</select>
<div [hidden]="semesterId.valid || semesterId.pristine" class="alert alert-danger">
学年学期不能为空
</div>
</div>
</div>
属性介绍:
$validng-valid Boolean 告诉我们这一项当前基于你设定的规则是否验证通过
$invalidng-invalid Boolean 告诉我们这一项当前基于你设定的规则是否验证未通过
$pristineng-pristine Boolean 如果表单或者输入框没有使用则为True
$dirtyng-dirty Boolean 如果表单或者输入框有使用到则为True