如何仅在最大长度问题上显示错误?

时间:2018-05-29 14:21:13

标签: angular5 angular-forms

这是我的模板:

<div *ngIf="isFieldValid('senderCity')" class="error">{{senderCityError}}</div>
                    <div *ngIf="isFieldMaxValid('senderCity')" class="error">Max 5 characters allowed.</div> 
                    <label *ngIf="canShowLabel('senderCity')" class="control-label">{{senderCityLabel}}</label>
                    <input type="text"  formControlName="senderCity"  class="form-control" placeholder="{{senderCityLabel}}" >

检查isFieldMaxValid - 错误我这样做:

isFieldMaxValid(field){
        return (this.quoteForm.get(field).valid && this.quoteForm.get(field).errors.maxLength )
    }

但不是炒作。如何返回maxlength的错误值?休息工作正常。

收到错误:

Cannot read property 'maxLength' of null

更新 我试过这个:它有效。

isFieldMaxValid(field){
        return (!this.quoteForm.get(field).valid && this.quoteForm.get(field).hasError('maxlength') );
    }

但是我得到了两个错误,如何让其中一个同时存在?

isFieldValid(field){
        return (!this.quoteForm.get(field).valid && !this.quoteForm.get(field).hasError('maxlength') && this.quoteForm.get(field).touched) || 
        (this.quoteForm.get(field).untouched && this.formSubmitAttempt);

    }

    isFieldMaxValid(field){
        return (!this.quoteForm.get(field).valid && this.quoteForm.get(field).hasError('maxlength') );
    }

1 个答案:

答案 0 :(得分:2)

您可以将html更新为:

<div *ngIf="isFieldValid('senderCity') && !isFieldMaxValid('senderCity')" class="error">{{senderCityError}}</div>
                    <div *ngIf="isFieldMaxValid('senderCity')" class="error">Max 5 characters allowed.</div> 
                    <label *ngIf="canShowLabel('senderCity')" class="control-label">{{senderCityLabel}}</label>
                    <input type="text"  formControlName="senderCity"  class="form-control" placeholder="{{senderCityLabel}}" > 

仅在maxLength错误不存在时显示无效错误。