没有名称为' control-name'的表单控件的值访问器

时间:2018-02-16 11:12:57

标签: angular angular2-formbuilder

我正在尝试学习如何在Angular 5中设计自定义表单控件,方法是遵循我找到的众多教程中的一个。但是,在每个教程结束时,我都会遇到标题中的错误:没有名称为' control-name'的表单控件的值访问器。到目前为止,这是我的代码。

APP-switch.html

<div (click)="switch()" class="switch" [attr.title]="label">
    <input type="checkbox" class="switch-input" [value]="value [attr.checked]="value" [attr.aria-label]="label">
    <span class="switch-label" data-on="On" data-off="Off"></span>
    <span class="switch-handle"></span>
</div>

APP-switch.ts

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

@Component({
  selector: 'app-switch',
  templateUrl: 'app-switch.html'
})
export class AppSwitchComponent implements ControlValueAccessor {
  @Input() label = 'switch';
  @Input('value') _value = false;
  onChange: any = () => {};
  onTouched: any = () => {};

  get value() {
    return this._value;
  }

  set value(val) {
    this._value = val;
    this.onChange(val);
    this.onTouched();
  }

  constructor() {}

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

  writeValue(value) {
    if (value)
      this.value = value;
  }

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

  switch() {
    this.value = !this.value;
  }
}

APP-switch.module.ts

import {forwardRef, NgModule} from '@angular/core';
import {TranslateModule} from "@ngx-translate/core";
import {AppSwitchComponent} from "./app-switch";
import {NG_VALUE_ACCESSOR} from "@angular/forms";

@NgModule({
  declarations: [
    AppSwitchComponent
  ],
  imports: [
    TranslateModule.forChild(),
  ],
  exports: [
    AppSwitchComponent
  ],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => AppSwitchComponent),
      multi: true
    }
  ]
})
export class AppSwitchComponentModule {
}

这就是我使用该组件的方式:

<form [formGroup]="myForm" (ngSubmit)="submit()">
    <app-switch formControlName="mySwitch" [label]="'My Switch'"></app-switch>
    <button>Submit</button>
</form>

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

我认为您需要将NG_VALUE_ACCESSOR提供程序放入AppSwitchComponent的providers数组中。像这样:

@Component({
    selector: 'app-switch',
    templateUrl: 'app-switch.html',
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => AppSwitchComponent),
            multi: true
        }
    ]
})