在Angular 2中创建自定义表单控件

时间:2016-10-12 22:05:13

标签: javascript angularjs forms angular

我正在尝试为<select>元素创建自定义表单控件组件(我意识到这不是创建自定义表单控件的最创新用法,但这仅用于测试目的)。我正在关注@ http://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html教程。

我的目标是在从<select-box>组件中选择一个值之前禁用提交按钮,但我认为我没有正确连接自定义表单控件,因为值没有当我选择不同的值时也不会更改,验证也不起作用(验证=自定义组件上的required HTML属性)。

见到目前为止我所拥有的内容。另外,http://plnkr.co/edit/TAxDyb8sHg158dXmyfwr?p=preview可以使用一个plunker。

谢谢!

主要组件

import {Component, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {SelectBoxComponent} from "./select-box.component";
import {FormsModule} from "@angular/forms";

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <form #form="ngForm" (ngSubmit)="log(form.value)">
        <select-box name="someValue" [ngModel]="someValue" required></select-box>
        <br>
        <button type="submit" [disabled]="!form.valid">Submit</button>
      </form>
      <br>
      {{ form.value | json }}
    </div>
  `,
})
export class App {
  name:string;
  someValue: any = 1;

  log(str) {
    console.log(str);
  }
}

@NgModule({
  imports: [ BrowserModule, FormsModule ],
  declarations: [ App, SelectBoxComponent ],
  bootstrap: [ App ]
})
export class AppModule {}

选择框组件

import { Component, forwardRef, Input } from "@angular/core";
import { SelectControlValueAccessor, NG_VALUE_ACCESSOR } from "@angular/forms";

@Component({
  selector: "select-box",
  template: `
    <select onchange="onChanged(event.target.value)" [ngModel]="ngModel">
      <option disabled selected value></option>
      <option value="1">1</option>
      <option value="2">2</option>
    </select>
  `,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => SelectBoxComponent),
      multi: true,
    }
  ],
})

export class SelectBoxComponent implements SelectControlValueAccessor {
  @Input() ngModel: any;

  onChanged(value) {
    this.ngModel = value;
    this.propagateChange(value);
  }

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

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

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

  registerOnTouched() {}
}

1 个答案:

答案 0 :(得分:6)

此处针对您的组件进行了修复:http://plnkr.co/edit/69SGnjYGBWhC4tEezc1G?p=preview

<select [(ngModel)]="selectValue">
  <option disabled selected value></option>
  <option value="1">1</option>
  <option value="2">2</option>
</select>

.ts

export class SelectBoxComponent implements ControlValueAccessor {
  private _selectValue: any = '';
  private _onTouchedCallback: () => {};
  private _onChangeCallback: (_:any) => {};

  get selectValue(): any {
    return this._selectValue;
  }
  set selectValue(value: any) {
    if (value !== this._selectValue) {
      this._inputValue = value;
      this._onChangeCallback(value);
    }

    this.hasValue = (value != null && value.length > 0)

     this._onTouchedCallback();

  }



  //From ControlValueAccessor interface
  writeValue(value: any) {
    this._selectValue = value;
  }

  //From ControlValueAccessor interface
  registerOnChange(fn: any) {
    this._onChangeCallback = fn;
  }

  //From ControlValueAccessor interface
  registerOnTouched(fn: any) {
    this._onTouchedCallback = fn;
  }
}

在您的选择组件中,存在一些错误。

  1. 您没有正确绑定模型。添加getter / setter,以便您跟踪更改并通过this._onChangeCallbackthis._onTouchedCallback();
  2. 进行通知
  3. 您需要注册registerOnTouched事件并触发它。这样,您的模型可以变为dirty,您的表单可以检测是否有效/无效。