1

就像标题所说的那样,如果我将输入包装在我的自定义组件中,Angular 的模板表单就不会接收到它。这是堆栈闪电战

这是来自 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 }}

自定义文本框.component.html

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

自定义文本框.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 = '';
}

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

在此处输入图像描述

4

1 回答 1

1

需要为 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);
  }
}

工作堆栈闪电战

于 2021-10-21T03:42:25.570 回答