无法将<mat-error>投影到自定义组件中

时间:2019-11-01 14:54:04

标签: angular typescript angular-material

我有一个使用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>

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

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

Screenshot of validation errors

这显然不是理想的,我的老板也不接受!我本以为这个问题已经解决了,因为它似乎很简单,但是在这种模式下我无法在www上找到任何示例。

我已经检查了Chrome中的DOM,并且在投射<mat-error>时似乎位于不同的位置,但是我不知道为什么。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

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

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