代码之家  ›  专栏  ›  技术社区  ›  3gwebtrain

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

  •  0
  • 3gwebtrain  · 技术社区  · 6 年前

    这是我的模板:

    <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 回复  |  直到 6 年前
        1
  •  2
  •   Yamini Chhabra    6 年前

    您可以将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错误时才显示无效错误。