【问题标题】:Cannot project <mat-error>s into a custom component无法将 <mat-error> 投影到自定义组件中
【发布时间】:2021-01-28 20:33:07
【问题描述】:

我有一个使用 Angular Material 的 Angular 8 应用程序。我正在尝试创建一个实现ControlValueAccessor 接口的可重用表单组件。它包含自己的具有两个控件的表单,如下所示:

<form [formGroup]="form">

  <mat-form-field>
    <mat-label>{{ nameLabel }}</mat-label>
    <input
      matInput
      type="text"
      formControlName="name"
      [disabled]="disabled"
      (blur)="onTouched()"/>
    <ng-content select="[name-errors]"></ng-content>
  </mat-form-field>

  <mat-form-field>
    <mat-label>{{ dateLabel }}</mat-label>
    <input
      matInput
      [matDatepicker]="picker"
      formControlName="plannedEnd"
      [disabled]="disabled"
      (blur)="onTouched()"
    />
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker></mat-datepicker>
    <ng-content select="[date-errors]"></ng-content>
  </mat-form-field>

</form>

及其 TypeScript:

import { ChangeDetectionStrategy, Component, forwardRef, Input, OnDestroy, OnInit } from '@angular/core';
import { ControlValueAccessor, FormBuilder, FormGroup, NG_VALUE_ACCESSOR } from '@angular/forms';
import { FormComponent, FormModel } from '@turntown/shared';

import * as moment from 'moment';
import { CreateScheduleReport } from '@turntown/cost-control/set-up/shared';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { MomentDateAdapter } from '@angular/material-moment-adapter';

@Component({
  selector: 'cc-name-and-date',
  templateUrl: './name-and-date.component.html',
  styleUrls: ['./name-and-date.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => NameAndDateComponent),
    multi: true,
  }],
})
export class NameAndDateComponent implements OnInit, FormComponent, ControlValueAccessor, OnDestroy {

  @Input() nameLabel: string;
  @Input() dateLabel: string;
  private readonly unsubscribe$ = new Subject<void>();

  disabled;
  form;
  onChange = (value: CreateScheduleReport) => {};
  onTouched = () => {};

  writeValue(newValue: CreateScheduleReport): void {
    this.form.setValue(newValue);
    this.onChange(newValue);
  }

  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }

  setDisabledState(isDisabled: boolean): void {
    this.disabled = isDisabled;
  }

  constructor(protected formBuilder: FormBuilder) {
  }

  ngOnInit() {
    this.form = this.initForm();
    this.onChange(this.form.value);

    this.form.valueChanges.pipe(
      takeUntil(this.unsubscribe$),
    ).subscribe(newFormValue => {
      this.onChange(newFormValue);
      this.onTouched();
    });
  }

  hasError(formControlName: string, error: string): boolean {
    MomentDateAdapter
    return this.form.get(formControlName).hasError(error) && this.form.get(formControlName).touched;
  }

  initForm(): FormGroup {
    const form: FormModel<CreateScheduleReport> = {
      name: [''],
      plannedEnd: [moment()],
    };
    return this.formBuilder.group(form);
  }

  submitForm(event: any): void {
  }

  ngOnDestroy(): void {
    this.unsubscribe$.next();
    this.unsubscribe$.complete();
  }
}

我正在像这样使用这个组件:

<form [formGroup]="form">

  <section class="first-reporting-period-details">
    <mat-card>
      <h1>First reporting period details</h1>
      <h3 tt-small>Planned end date of period</h3>

      <cc-name-and-date
        nameLabel="Period Name"
        dateLabel="Period End Date"
        formControlName="period">
        <ng-container name-errors>
          <mat-error *ngIf="hasError('period', 'invalidPeriodName')">
            This is mandatory
          </mat-error>
        </ng-container>
        <ng-container date-errors>
          <mat-error *ngIf="hasError('period', 'invalidPeriodDate')">
            The first reporting period end date must be today or later
          </mat-error>
        </ng-container>
      </cc-name-and-date>
    </mat-card>
  </section>

  <section class="first-stage-details">
    <mat-card>
      <h1>First stage details</h1>
      <h3 tt-small>Planned end date of stage</h3>
      <cc-name-and-date
        nameLabel="Stage Name"
        dateLabel="Stage End Date"
        formControlName="stage">
        <ng-container name-errors>
          <mat-error *ngIf="hasError('stage', 'invalidStageName')">
            This is mandatory
          </mat-error>
        </ng-container>
        <ng-container date-errors>
          <mat-error *ngIf="form.hasError('invalidStageDate')">
            The first stage end date must be the same as the first reporting period end date or later
          </mat-error>
        </ng-container>
      </cc-name-and-date>
    </mat-card>
  </section>

</form>

如您所见,我正在尝试在容器组件中执行验证逻辑,并尝试使用内容投影将错误传递给子组件。

所有这些逻辑都有效,但不幸的是,投射的错误无法在浏览器中正确呈现。当发生验证错误时,消息会在表单控件内部呈现,如下所示:

这显然不理想,也不能让我的老板接受!我原以为这个问题会得到解决,因为它看起来是一个足够简单的模式,但是我在 www 上找不到任何使用这种模式的示例。

我检查了 Chrome 中的 DOM,似乎&lt;mat-error&gt;s 在投影时位于不同的位置,但我不知道为什么。有人可以帮忙吗?

【问题讨论】:

  • 这是一个已有 2 年历史的已知错误。 github 上有一个未解决的问题。
  • 有什么解决办法吗?
  • @Stavm 我认为这不是同一个问题。我是一个有角度的初学者,但可能是ng-content 的分辨率发生在mat-form-field 元素的填充之后?

标签: angular typescript angular-material


【解决方案1】:

您是否尝试将&lt;ng-container&gt; 放入&lt;mat-error&gt; 中? 我试图为自定义错误制作一个组件并像这样使用它

<mat-error>
   <form-error [control]="formGroup.controls.type" field="Name"></form-error>
</mat-error>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-27
    • 1970-01-01
    • 1970-01-01
    • 2012-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多