Angular Material 输入文本框包装器以与 ControlValueAccessor 和内部 formControlName 一起使用

Angular Material Input Textbox Wrapper to work with ControlValueAccessor and inner formControlName

我正在尝试让 ControlValueAccessor 和 formControlName 与客户 Material 输入文本框一起工作。 出于某种原因,代码无法正常工作,正在尝试修复它。阅读大量教程,并应用 ControlValueAccsor。 我们应该使用 MAT_INPUT_VALUE_ACCESSOR 吗? Material Angular 最简单的解决方法是什么?

目标是让这个程式化的文本框与表单一起使用。

打字稿:

import { Component, OnInit, Input, ViewChild, EventEmitter, Output, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
  selector: 'app-input-textbox',
  templateUrl: './input-textbox.component.html',
  styleUrls: ['./input-textbox.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => InputTextboxComponent),
      multi: true
    }
  ]
})

export class InputTextboxComponent implements OnInit, ControlValueAccessor {
  @Input() MaxLength: string;
  @Input() Disabled: boolean;
  @Input() ReadOnly: boolean;
  @Input() NgClass:string;
  @Input() Value: string;
  @Input() type: string;
  @Input() Label: string;
  @Input() PlaceHolder: string;
  @Output() saveValue = new EventEmitter();
  @Output() onStateChange = new EventEmitter();

  disabled: boolean;

  constructor() { }

  ngOnInit() {
  }

  saveValueAction(e) {
    this.saveValue.emit(e.target.value);
  }

  onChange(e) {
    this.Value = e;
  }

  onTouched() {
    this.onStateChange.emit();
  }

  writeValue(value: any) {
    this.Value = value ? value : '';
  }

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

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

  setDisabledState(isDisabled) { this.disabled = isDisabled; }
}

HTML:

<div class="input-wrap">
    <mat-form-field appearance="outline">
        <mat-label>{{Label}}</mat-label>   
        <input matInput 
            [attr.maxlength] = "MaxLength"
            [value]="Value ? Value : ''"
            [placeholder]="PlaceHolder ? PlaceHolder : ''"
            [readonly]="ReadOnly"
            [ngClass]="NgClass"
            [type]="type ? type: 'text'"
        >
    </mat-form-field>
</div>

表单组没有从 InputTextboxComponent 接收值的原因是因为每次 input 元素从用户接收新值时都没有调用 onChange 方法.我为 InputTextboxComponent 内的 input 元素添加了一个 on-change 事件侦听器,并从那里调用了 onChange 方法。 (input-text-box.component.ts 的第 58 行)

示例:https://stackblitz.com/edit/angular-h4ebkp