我创建了一个Angular被动表单并使用ngClass
,我根据表单字段是否有效添加了Bootstrap的has-success
和has-error
类
/*checks if data inthe field is valid or not*/
isFieldValid(field: string) {
let fieldValid:boolean = this.signupForm.get(field).valid && this.signupForm.get(field).touched;
console.log("isFieldValid for "+field+" returning "+fieldValid);
return fieldValid;
}
/*add css to this control depending on whether it is valid or not*/
displayFieldCss(field: string) {
console.log("in displayFieldCss for field "+field);
let fieldValid:boolean = this.isFieldValid(field);
return {
'has-error': !fieldValid, // if fieldvalid returns false i.e. field is not valid then we want has-error css. So set it to true (opp. of fieldValid)
'has-success': fieldValid //if fieldvalid returns true i.e. field is valid then we want has-success css. So set it to true (value of fieldValid)
//'has-feedback': this.isFieldValid(field)
}
HTML
<label for="firstname" class="control-label required">First Name</label>
<input id="firstname" type="text" class="form-control" formControlName="firstName" [ngClass]="displayFieldCss('firstName')" required>
<app-show-errors [control]="signupForm.controls.firstName"></app-show-errors>
在浏览器中检查元素时,我可以看到正在添加类。
如果字段为空,则检查元素
<input _ngcontent-c7="" class="form-control ng-pristine ng-invalid ng-touched has-error" formcontrolname="firstName" id="firstname" required="" ng-reflect-klass="form-control" ng-reflect-ng-class="[object Object]" ng-reflect-required="" ng-reflect-name="firstName" type="text">
如果字段为空,则检查元素
<input _ngcontent-c7="" class="form-control ng-touched ng-dirty ng-valid has-success" formcontrolname="firstName" id="firstname" required="" ng-reflect-klass="form-control" ng-reflect-ng-class="[object Object]" ng-reflect-required="" ng-reflect-name="firstName" type="text">
但我不会看到input
文本框的边框为has-error
的红色或has-success
的绿色。这不是Bootstrap的默认行为,还是我需要为此提供css
?
答案 0 :(得分:1)
似乎在bootstrap4中,has-error和has-succes被删除了。改为使用“is-valid”和“is-invalid”:
...
return {
'is-invalid': !fieldValid, // if fieldvalid returns false i.e. field is not valid then we want has-error css. So set it to true (opp. of fieldValid)
'is-valid': fieldValid //if fieldvalid returns true i.e. field is valid then we want has-success css. So set it to true (value of fieldValid)
//'has-feedback': this.isFieldValid(field)
}
...