一般来说前端界面少不了一两个输入框,这篇说说输入框字体长度限制的问题
准备工作
1、安装模块
npm install ng2-validation –save
2、配置*.module.ts
import { FormsModule,ReactiveFormsModule } from '@angular/forms';
import {CustomFormsModule} from "ng2-validation";
...
imports: [
FormsModule,CustomFormsModule,ReactiveFormsModule
],...
方式一、这个需要对应上 ,第一个input那些绑定需要和ts对应,之后是逻辑判断 ! ngif
html
<div class="col-md-12 search">
<form #myForm="ngForm">
<div>
<input type="text" [(ngModel)]="form.field" name="field" #field="ngModel" [rangeLength]="[0,30]" class="form-control" required placeholder="可以输入课程名称、上课时间、授课老师、学分进行查看(少于30字)"/>
<input type="button" [disabled]="!myForm.form.valid" class="btn btn-primary" (click)="query($event)" value="查询">
<div class="text-danger" *ngIf="field.errors?.rangeLength">输入字符长度在0-30之间</div>
</div>
</form>
</div>
ts
import {FormControlName,FormControl,FormGroup,FormArray,NgForm,FormBuilder,Validators} from "@angular/forms";
// 2. 引入ng2-validation中的组件
import {CustomValidators} from 'ng2-validation';
// 3. 定义表单组
form:FormGroup;
constructor(private router:Router,private confirmService: ConfirmationService) {
let fb=new FormBuilder();
this.form = fb.group({
// 定义form.field 是一个区间
field: new FormControl('',CustomValidators.range([0,30]))
}); }
方式二、这个对应关系少了一点,不过还是要注意的,这个逻辑判断hidden加了一些复杂性。
html
<div class="col-md-12 search">
<form [formGroup]="formModel" novalidate>
<div class="form-group" [class.has-error]="formModel.hasError('minlength','title') && formModel.hasError('maxlength','title') " >
<input formControlName="title" type="text" class="form-control" placeholder="可以输入课程名称、上课时间、授课老师、学分进行查看(少于30字)"/>
<!--这个是提交按钮,如果条件不满足,提价按钮为只读-->
<input type="button" [disabled]="!formModel.valid" class="btn btn-primary" (click)="query($event)" value="查询">
<div [hidden]=" formModel.get('title').untouched && (!formModel.hasError('minlength','title') && !formModel.hasError('maxlength','title')) "> 请输入至少1-30个字</div>
</div>
</form>
</div>
ts
formModel:FormGroup;
constructor(private router:Router,private confirmService: ConfirmationService) { let fb=new FormBuilder(); this.formModel = fb.group({ title:['',[Validators.required,Validators.minLength(1),Validators.maxLength(30)]] }) }
http://www.jb51.cc/article/p-qoonswjs-d.html
http://blog.csdn.net/kuangshp128/article/details/72912009
http://www.runoob.com/angularjs/angularjs-model.html