如何创建自定义的反应形式元素?

时间:2019-01-14 18:50:23

标签: angular angular-reactive-forms controlvalueaccessor

我正在使用Angular中的Reactive Forms,并且试图创建一个自定义表单元素,以便可以在表单中使用按钮。我正在尝试遵循Alligator.io的教程,但尚不清楚如何将其集成到我的组件中。目前,我收到以下错误。

ERROR Error: No value accessor for form control with name: 'coverage_for_domestic_partners'

下面是我的代码,将不胜感激。

// HTML

<div class="button-group" [formGroup]="group">
    <button
        *ngFor="let option of config.options"
        class="button button--toggle"
        [ngClass]='{"is-active": option.selected}'
        (click)="select($event, option)"
        [formControlName]="config.key">
        <div class="button-content">{{option.key}}</div>
    </button>
</div>

//组件

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

@Component({
 selector: 'z-toggle-group',
 templateUrl: './z-toggle-group.component.html',
 styleUrls: ['./z-toggle-group.component.scss'],
 providers: [
{
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => ZToggleGroupComponent),
  multi: true
}
  ]


 })
export class ZToggleGroupComponent implements OnInit, ControlValueAccessor {

@Input() config;
@Input() group: FormGroup;

@Input() disabled = false;
  @HostBinding('style.opacity')
  get opacity() {
    return this.disabled ? 0.25 : 1;
  }

clicked;

onChange = (rating: number) => {};
onTouched = () => {};

constructor() { }

ngOnInit() {
    // console.log('form', this.group)
      this.group.get(this.config.key).valueChanges.subscribe(value => {
        console.log('formValue', value);
    })
}

    writeValue(obj: any): void {
        throw new Error("Method not implemented.");
    }
    registerOnChange(fn: any): void {
        throw new Error("Method not implemented.");
    }
    registerOnTouched(fn: any): void {
        throw new Error("Method not implemented.");
    }
    setDisabledState?(isDisabled: boolean): void {
        throw new Error("Method not implemented.");
    }

select($event, option) {
    this.clicked = $event;
    this.group.get(this.config.key).patchValue(option.value, {onlySelf: true});

    this.config.options.forEach(option => {
        option.selected = false;
    })

    option.selected = true;
}

}

1 个答案:

答案 0 :(得分:1)

您需要实现ControlValueAccessor接口,为此,您将需要实现以下方法:

interface ControlValueAccessor {
  writeValue(obj: any): void
  registerOnChange(fn: any): void
  registerOnTouched(fn: any): void
  setDisabledState(isDisabled: boolean)?: void
}

您可以看到我的示例实现权here

当组件的值更改时,您必须调用在ts文件中注册的OnChange方法。

您可以看到我的通话示例here

此后,您可以通过表单内的标记选择器(在您的情况下为z-toggle-group)来使用组件,然后就可以使用formControlName

<div class="button-group" [formGroup]="group">
    <button
        *ngFor="let option of config.options"
        class="button button--toggle"
        [ngClass]='{"is-active": option.selected}'
        (click)="select($event, option)">

        <z-toggle-group [formControlName]="config.key"></z-toggle-group>

        <div class="button-content">{{option.key}}</div>
    </button>
</div>

Here是您的代码。