Angular - 包装在自定义组件中的输入在模板驱动形式中不起作用

Angular - input wrapped in custom component not working in template driven form

正如标题所说,如果我在我的自定义组件中包装了一个输入,它不会被 Angular 的模板表单拾取。这是 stackblitz

这是来自 StackBlitz 的一些代码

app.component.html

<div ngForm #myForm="ngForm">
  <app-custom-textbox
    customName="wrappedInput"
    customValue="wrapped"
  ></app-custom-textbox>
  <hr />
  <input name="noWrapper" [(ngModel)]="message" />
</div>
<hr />
<p>myForm.value is below:</p>
{{ myForm.value | json }}

custom-textbox.component.html

<p>My custom textbox component</p>
<input type="textbox" name="{{ customName }}" [(ngModel)]="customValue" />

custom-textbox.component.ts

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-custom-textbox',
  templateUrl: './custom-textbox.component.html',
})
export class CustomTextboxComponent {
  @Input() customName: string = '';
  @Input() customValue: string = '';
}

我希望在 myForm.value 输出中看到 wrappedInputnoWrapper 属性,但只有 noWrapper 被拾取。

需要为 CustomTextBoxComponent 实现 ControlValueAccessor,如下所示:~

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

@Component({
  selector: 'app-custom-textbox',
  templateUrl: './custom-textbox.component.html',
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => CustomTextboxComponent),
      multi: true,
    }
  ],
})
export class CustomTextboxComponent implements ControlValueAccessor {
  @Input() customValue: string = '';

  propagateChange = (_: any) => {};
  public onTouched: any = () => {};

  writeValue(obj: any): void {
    this.customValue = obj;
  }

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

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

  onModelChange(val: any) {
    this.propagateChange(val);
  }
}

Working Stackblitz