Angular ng-content не работает с mat-form-field

Sep 15 2020

Моя цель:

Я пытаюсь создать многоразовое поле mat-form-field с четкой кнопкой.

Как я пытался достичь своей цели:

Я создал компонент «mat-clearable-input» и использовал его так:

<mat-clearable-input>
        <mat-label>Put a Number here pls</mat-label>
        <input matInput formControlName="number_form_control">
    </mat-clearable-input>

mat-clearable-input.component.html

<mat-form-field>
    <ng-content></ng-content>
</mat-form-field>

Ожидаемый результат :

Тег ng-content принимает метку и ввод и помещает их в тег mat-form-field.

Фактический результат :

Error: mat-form-field must contain a MatFormFieldControl.
    at getMatFormFieldMissingControlError (form-field.js:226)
    at MatFormField._validateControlChild (form-field.js:688)
    at MatFormField.ngAfterContentChecked (form-field.js:558)
    at callHook (core.js:2926)
    at callHooks (core.js:2892)
    at executeInitAndCheckHooks (core.js:2844)
    at refreshView (core.js:7239)
    at refreshComponent (core.js:8335)
    at refreshChildComponents (core.js:6991)
    at refreshView (core.js:7248)

Похоже, мне чего-то не хватает и я неправильно использую тег ng-content.

Мне не удалось найти документацию по тегу ng-content на веб-сайте angular.

Спасибо за любую помощь.

ИЗМЕНИТЬ ПОСЛЕ ОТВЕТА НИЖЕ

Итак, я попробовал этот предложенный метод:

export class MatClearableInputComponent implements OnInit {
  @ContentChild(MatFormFieldControl) _control: MatFormFieldControl<any>;
  @ViewChild(MatFormField) _matFormField: MatFormField;
  // see https://stackoverflow.com/questions/63898533/angular-ng-content-not-working-with-mat-form-field/
  ngOnInit() {
    this._matFormField._control = this._control;
  }

}

к сожалению, когда я пытаюсь использовать это в форме, он все равно терпит неудачу с ошибкой «Ошибка: поле-формы-мат должно содержать MatFormFieldControl».

Код, в котором я пытаюсь использовать этот компонент в форме:

<mat-clearable-input>
    <mat-label>Numero incarico</mat-label>
    <buffered-input matInput formControlName="numero"></buffered-input>
</mat-clearable-input>

Репродукция на stackblitz: https://stackblitz.com/edit/angular-material-starter-xypjc5?file=app/clearable-form-field/clearable-form-field.component.html

обратите внимание, как не работают функции mat-form-field (без контура, без плавающей метки), также откройте консоль, и вы увидите ошибку Error: mat-form-field должно содержать MatFormFieldControl.

ИЗМЕНИТЬ ПОСЛЕ РАЗМЕЩЕНИЯ ВАРИАНТА 2

Я пробовал это сделать:

<mat-form-field>
  <input matInput hidden>
  <ng-content></ng-content>
</mat-form-field>

Это работает, но затем, когда я добавил матовую метку в свое поле формы, например:

<mat-clearable-input>
        <mat-label>Numero incarico</mat-label>
        <buffered-input matInput formControlName="numero"></buffered-input>
    </mat-clearable-input>

этикетка никогда не плавает, а просто остается там, как обычно, все время.

Итак, я попытался назначить this._matFormField._control._labelдочернему контенту с меткой, но это не сработало, потому что _label является частным и для него нет установщика.

Похоже, мне не повезло, и это невозможно сделать в Angular без особых усилий.

Если у вас есть дальнейшие идеи, не стесняйтесь форк stackblitz и попробуйте!

Изменить после ответа @evilstiefel

решение работает только для родных <input matInput>. Когда я пытаюсь заменить это своим пользовательским компонентом ввода, он больше не работает.

Рабочая установка:

<mat-form-field appClearable>
    <mat-label>ID incarico</mat-label>
    <input matInput formControlName="id">
</mat-form-field>

Та же настройка, но с моим пользовательским компонентом "буферизованный ввод" (не работает :()

<mat-form-field appClearable>
    <mat-label>ID incarico</mat-label>
    <buffered-input matInput formControlName="id"></buffered-input>
</mat-form-field>

Консоль регистрирует эту ошибку, когда я нажимаю кнопку очистки:

TypeError: Cannot read property 'ngControl' of undefined
    at ClearableDirective.clear (clearable.directive.ts:33)
    at ClearButtonComponent.clearHost (clearable.directive.ts:55)
    at ClearButtonComponent_Template_button_click_0_listener (clearable.directive.ts:47)
    at executeListenerWithErrorHandling (core.js:14293)
    at wrapListenerIn_markDirtyAndPreventDefault (core.js:14328)
    at HTMLButtonElement.<anonymous> (platform-browser.js:582)
    at ZoneDelegate.invokeTask (zone-evergreen.js:399)
    at Object.onInvokeTask (core.js:27126)
    at ZoneDelegate.invokeTask (zone-evergreen.js:398)
    at Zone.runTask (zone-evergreen.js:167)

Ответы

1 evilstiefel Sep 29 2020 at 09:16

Другое решение - использовать директиву для реализации поведения.

import {
  AfterViewInit,
  Component,
  ComponentFactory,
  ComponentFactoryResolver,
  ContentChild,
  Directive,
  Injector,
  Input,
  Optional,
  SkipSelf,
  TemplateRef,
  ViewContainerRef,
} from '@angular/core';
import { MatFormFieldControl } from '@angular/material/form-field';


@Directive({
  selector: '[appClearable]'
})
export class ClearableDirective implements AfterViewInit {

  @ContentChild(MatFormFieldControl) matInput: MatFormFieldControl<any>;
  @Input() appClearable: TemplateRef<any>;
  private factory: ComponentFactory<ClearButtonComponent>;

  constructor(
    private vcr: ViewContainerRef,
    resolver: ComponentFactoryResolver,
    private injector: Injector,
  ) {
    this.factory = resolver.resolveComponentFactory(ClearButtonComponent);
  }

  ngAfterViewInit(): void {
    if (this.appClearable) {
      this.vcr.createEmbeddedView(this.appClearable);
    } else {
      this.vcr.createComponent(this.factory, undefined, this.injector);
    }
  }

  /**
   * This is used to clear the formControl oder HTMLInputElement
   */
  clear(): void {
    if (this.matInput.ngControl) {
      this.matInput.ngControl.control.reset();
    } else {
      this.matInput.value = '';
    }
  }
}

/**
 * This is the markup/component for the clear-button that is shown to the user.
 */
@Component({
  selector: 'app-clear-button',
  template: `
  <button (click)="clearHost()">Clear</button>
  `
})
export class ClearButtonComponent {
  constructor(@Optional() @SkipSelf() private clearDirective: ClearableDirective) { }

  clearHost(): void {
    if (this.clearDirective) {
      this.clearDirective.clear();
    }
  }
}

Это создает директиву с именем appClearableи необязательный компонент для резервного макета. Обязательно добавьте компонент и директиву в declarationsмассив вашего модуля. Вы можете либо указать шаблон, который будет использоваться для предоставления пользовательского интерфейса, либо просто использовать его ClearButtonComponentкак универсальное решение. Разметка выглядит так:

<!-- Use it with a template reference -->
<mat-form-field [appClearable]="clearableTmpl">
  <input type="text" matInput [formControl]="exampleInput">
</mat-form-field>

<!-- use it without a template reference -->
<mat-form-field appClearable>
  <input type="text" matInput [formControl]="exampleInput2">
</mat-form-field>

<ng-template #clearableTmpl>
  <button (click)="exampleInput.reset()">Marked-Up reference template</button>
</ng-template>

Это работает с ngControl / FormControl и без него, но вам может потребоваться настроить его для вашего варианта использования.

2 Akash Sep 24 2020 at 12:46

Обновление :

Вариант 1 не работает для новых версий angular, потому что @ViewChild()в ngOnInit()хуке возвращается undefined . Еще одна хитрость - использовать манекен MatFormFieldControl-

Вариант 2

<mat-form-field>
  <input matInput hidden>
  <ng-content></ng-content>
</mat-form-field>

Редактировать :

Эта ошибка возникает из-за того, что MatFormFieldкомпонент запрашивает дочерний контент, используя @ContentChild(MatFormFieldControl)который не работает, если вы используете вложенный ng-content( MatFormField также использует проекцию контента ).

Вариант 1 (не рекомендуется)

Ниже показано, как вы можете заставить его работать -

@Component({
  selector: 'mat-clearable-input',
  template: `
    <mat-form-field>
      <ng-content></ng-content>
    </mat-form-field>
  `
})
export class FieldComponent implements OnInit { 
    @ContentChild(MatFormFieldControl) _control: MatFormFieldControl<any>;
    @ViewChild(MatFormField) _matFormField: MatFormField;

    ngOnInit() {
        this._matFormField._control = this._control;
    }
}

Пожалуйста, ознакомьтесь с этим стеком Blitz . Кроме того, эта проблемаgithub уже создана .