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

How to show an error only on max length issue?

这是我的模板:

<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 )
    }

但是不行。如何 return 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') );
    }

你可以这样更新你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 错误时显示无效错误。