如何在 Angular 中为反应式表单构建可重用字段

How to build reusable field for reactive form in Angular

我正在尝试为响应式表单构建一个可重用的字段组件,但我无法从 custom-input 组件中获取值。

<form [formGroup]="form" (ngSubmit)="submit()">
  <custom-input id="name" name="name" formControlName="name"></custom-input>
  <button type="submit" name="button">Submit</button>
</form>

我的自定义输入可重用组件

import { Component, OnInit, Input } from '@angular/core';
import { FormControl } from "@angular/forms";

@Component({
  selector: 'custom-input',
  template: '<input type="text" [class]="class" [id]="id" [name]="name" [formControlName]="formControlName">',
  styles: []
})
export class CustomInputComponent implements OnInit {
  @Input() public id: string;
  @Input() public class: string;
  @Input() public name: string;
  @Input() public formControlName: string;

  constructor() { }

  ngOnInit() {
  }
}

您可以实现 ControlValueAccessor,但可能不想 re-implement 本机输入的方法。为此,您可以使用 FormControlDirective 访问 valueAccessor。

formControlformControlName 被添加为输入属性,因此它在这两种情况下都适用。如果提供 formControlName,将从 ControlContainer.

中检索 FormControl 的实例
@Component({
      selector: 'app-custom-input',
      template: `<input type="text" [formControl]="control">`,
      styleUrls: ['./custom-input.component.scss'],
      providers: [
        {
          provide: NG_VALUE_ACCESSOR,
          useExisting: CustomInputComponent,
          multi: true
        }
      ]
    })
    export class CustomInputComponent implements ControlValueAccessor {
      @Input() formControl: FormControl;
      @Input() formControlName: string;
    
      @ViewChild(FormControlDirective, {static: true})
      formControlDirective: FormControlDirective;
      private value: string;
      private disabled: boolean;
    
      constructor(private controlContainer: ControlContainer) {
      }
    
      get control() {
        return this.formControl || this.controlContainer.control.get(this.formControlName);
      }
    
    
      registerOnTouched(fn: any): void {
        this.formControlDirective.valueAccessor.registerOnTouched(fn);
      }
    
      registerOnChange(fn: any): void {
        this.formControlDirective.valueAccessor.registerOnChange(fn);
      }
    
      writeValue(obj: any): void {
        this.formControlDirective.valueAccessor.writeValue(obj);
      }
    }

来源:https://medium.com/angular-in-depth/dont-reinvent-the-wheel-when-implementing-controlvalueaccessor-a0ed4ad0fafd