【问题标题】:A reusable Reactive Form Error Validation Component doesn't show the messages可重用的反应式表单错误验证组件不显示消息
【发布时间】: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


【解决方案1】:

如果有错误,输入的类 is-invalid 被激活并且我看到一个红色边框,但是,可重用的错误组件没有显示消息。我认为原因与引导程序和class="invalid-feedback"有关。

这正是原因。

从模板中删除class="invalid-feedback"

<ng-container *ngFor="let validation of errorMessages">
  <div *ngIf="control.hasError(validation.type) && (control.dirty || control.touched)">
    {{validation.message}}
  </div>
</ng-container>

在组件指令中添加了相同的内容

@Component({
  selector: 'app-error-message-container',
  host: { class: 'invalid-feedback' },
  templateUrl: './error-message-container.component.html',
  styleUrls: ['./error-message-container.component.scss']
})
export class ErrorMessageContainerComponent implements OnInit {
  ...
}

问题已解决

编码愉快!

【讨论】:

  • 感谢您的帮助。您能否添加更多关于您做了什么以及为什么添加主机属性使其工作的详细信息?我不明白。另外,我不知道错误模板中的class="invalid-feedback" 不起作用的原因。请注意:TSlint 说“使用@HostBinding 或@HostListener 而不是host 元数据属性”,知道吗?
  • 欢迎您!不得不挖掘invalid-feedback 类。 CSS 属性的编码方式是,它需要是input-group 的直接子级才能定位在其中的正确位置。将它放在其他地方会呈现 display:none 隐藏内容。
  • 至于TSlint,可以阅读stackoverflow.com/questions/45172565/…
【解决方案2】:

在您的ErrorMessageContainerComponent 中,您的invalid-feedback 类将display 属性设置为none,因为它不是输入元素的兄弟。如果您仍想应用 Bootstrap 4 中的 invalid-feedback 类样式,可以使用 class="invalid-feedback d-block" 手动设置显示。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-13
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 2019-06-11
    相关资源
    最近更新 更多