在Angular 2中创建自定义表单控件 [英] Creating custom form controls in Angular 2
问题描述
我正在尝试为<select>
元素创建自定义表单控件组件(我意识到这不是创建自定义表单控件的最具创新性的用途,但这只是出于测试目的).我正在跟着教程@
I'm trying to create a custom form control component for a <select>
element (I realize this isn't the most innovative use of creating a custom form control, but this is just for testing purposes). I'm following along with the tutorial @ http://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html.
我的目标是禁用提交按钮,直到从<select-box>
组件中选择了一个值,但是我认为我没有正确连接自定义表单控件,因为该值不正确当我选择其他值时更改,验证也不起作用(验证=自定义组件上的required
HTML属性).
What I'm aiming for is to have the submit button disabled until a value has been selected from the <select-box>
component, but I don't think I have the custom form control wired up properly as the value doesn't change when I select a different value nor does the validation work (validation = just a required
HTML attribute on the custom component).
请参阅下文,了解到目前为止的内容.另外,您也可以在 http://plnkr.co/edit/TAxDyb8sHg158dXmyfwr?p=preview
See below for what I have so far. Alternatively a plunker is available at http://plnkr.co/edit/TAxDyb8sHg158dXmyfwr?p=preview.
谢谢!
主要组件
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() {}
}
推荐答案
以下是针对您的组件的修复程序: http://plnkr.co/edit/69SGnjYGBWhC4tEezc1G?p=preview
Here a fix for your component: 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;
}
}
在您的选择组件中,有一些错误.
In your select component, there are a few mistakes.
- 您没有正确绑定模型.添加getter/setter,以便您可以跟踪更改并通过
this._onChangeCallback
和this._onTouchedCallback();
通知它
- 您需要注册
registerOnTouched
事件并触发它.这样,您的模型可以变为dirty
,并且您的表单可以检测到更改是否有效.
- you are not binding the model properly. Add getter/setter so it's possible for you to track changes and notify it with
this._onChangeCallback
andthis._onTouchedCallback();
- You need to register
registerOnTouched
event and trigger it. That way, your model can becomedirty
and your form can detect changes whether valid/invalid.
这篇关于在Angular 2中创建自定义表单控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!