我了解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>
答案 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>