maxLengh或所需的验证通过模板验证失败后,如何向特定的div显示错误消息?

时间:2018-11-11 20:58:47

标签: javascript angular

我了解Angular可以通过html模板进行验证并输出验证错误

但是,如果我在组件html上有一个div,并且在组件类中有一个errorMessage属性,并且希望在该div中输出所有验证错误,该怎么办呢?目标?

  <div class="errorMessage">...</div>

  <input id="name" type="text" placeholder="name" #name [(ngModel)]="account.name"
         name="name" (click)="clearErrors()" maxlength="40" required>

  <div *ngIf="name.invalid && (name.dirty || name.touched)">

    <div *ngIf="name.errors.required">
      Account name cannot be empty.    <-- like to show this msg on div.errorMessage
    </div>
    <div *ngIf="name.errors.maxlength">
      Account name maximum length exceeded. <-- like to show this msg on div.errorMessage
    </div>
  </div>

1 个答案:

答案 0 :(得分:1)

您只需将错误部分移到所需的消息容器中即可。

  <div class="errorMessage">
        <ng-container *ngIf="name.invalid && (name.dirty || name.touched)">
            <ng-container *ngIf="name.errors.required">
                Account name cannot be empty. </ng-container>
            <ng-container *ngIf="name.errors.maxlength">
                Account name maximum length exceeded.
            </ng-container>
        </ng-container>
    </div>

    <input id="name" type="text" placeholder="name" #name 
           [(ngModel)]="account.name"
             name="name" (click)="clearErrors()" 
            maxlength="40" required>