【发布时间】:2020-05-10 20:58:01
【问题描述】:
我在 Angular 8 中做一个 Web 应用程序,我想要一个可重用的组件来只显示我的 FormControl 的错误,以避免在很多地方重复这个逻辑。我正在使用bootstrap v4.4.1。
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<div class="input-group">
<label for="emailInput" class="sr-only">Email</label>
<input id="emailInput"
formControlName="email"
type="email"
class="form-control"
[ngClass]="{
'is-invalid': form.get('email').invalid && (form.get('email').dirty || form.get('email').touched)
}"
placeholder="Email"
required
autofocus>
// Reusable component to show errors
<app-error-message-container [control]="form.get('email')" errorMessagesKeyName="email"></app-error-message-container>
</div>
<button type="submit" class="btn btn-primary btn-block mt-3">Log in</button>
</form>
可重用的错误消息组件:
import {Component, Input, OnInit} from '@angular/core';
import {AbstractControl} from '@angular/forms';
const FORM_VALIDATION_MESSAGES = {
email: [
{type: 'required', message: 'Is required.'},
{type: 'pattern', message: 'No pattern.'}
],
};
@Component({
selector: 'app-error-message-container',
templateUrl: './error-message-container.component.html',
styleUrls: ['./error-message-container.component.scss']
})
export class ErrorMessageContainerComponent implements OnInit {
@Input() control: AbstractControl;
@Input() errorMessagesKeyName: string;
errorMessages: { type: string, message: string }[];
constructor() {
}
ngOnInit() {
this.errorMessages = FORM_VALIDATION_MESSAGES[this.errorMessagesKeyName];
}
}
模板
<ng-container *ngFor="let validation of errorMessages">
<div *ngIf="control.hasError(validation.type) && (control.dirty || control.touched)"
class="invalid-feedback">
{{validation.message}}
</div>
</ng-container>
stackblitz 上的演示:https://stackblitz.com/edit/angular-ivy-dnmnpk
如果有错误,输入的类is-invalid 被激活并且我看到一个红色边框,但是,可重用的错误组件没有显示消息。我认为原因与引导程序和class="invalid-feedback"有关。
如果我不使用可重用组件来显示错误消息,一切都会按预期工作,如下所示:
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<div class="input-group">
<label for="emailInput" class="sr-only">Email</label>
<input id="emailInput"
formControlName="email"
type="email"
class="form-control"
[ngClass]="{
'is-invalid': form.get('email').invalid && (form.get('email').dirty || form.get('email').touched)
}"
placeholder="Email"
required
autofocus>
// Is showing correctly
<div *ngIf="form.get('email').hasError('required') && (form.get('email').dirty || form.get('email').touched)" class="invalid-feedback">
There is an error!
</div>
</div>
我的目标是能够使用可重用组件通过引导程序正确显示错误。
【问题讨论】:
-
我在 Angular Material Reactive 表单上实现了类似的东西。您需要将验证函数作为参数传递。我将与 stackblitz 合作并发布它
标签: angular bootstrap-4