问题描述
我想创建一个自定义的InputCustom
组件,并使用它来创建模型驱动的表单.
I want to create a custom InputCustom
component and use it to create model-driven forms.
我的自定义组件只是包装了一个输入字段,并使用Bootstrap material design
进行外观显示.
My custom component just wraps an input field and uses Bootstrap material design
for look'n'feel.
@Component({
selector:'inputCustom',
template:`
<div class="form-group label-floating is-empty">
<label class="control-label" for="input">Type here</label>
<input class="form-control" id="input" type="text">
<p class="help-block">Some help text</p>
<span class="material-input"></span>
</div>
`})
class InputCustom{....}
在 Angular2 中,当您创建模型驱动的表单时
In Angular2 when you create a model-driven form
<form [ngFormModel]="formRef">
<input type ="email" ngControl="email">
</form>
表单元素上存在的所有
所有Controls
均已注册到ControlGroup
中.通过使用 formRef ,您可以跟踪控制器内部的字段值.
all Controls
present on form elements are registered into a ControlGroup
. By using the formRef you can track field values inside controllers.
@Component({...})
class FormController{
formRef: ControlGroup;
constructor(...){
this.form.valueChanges.subscribe(data => console.log('changes', data));
}
}
现在,我希望人们像这样使用我的组件
Now, I want people to use my component like this
<form [ngFormModel]="formRef">
<inputCustom type ="email" ngControl="email">
</form>
Q1:我需要编写自己的自定义ngControl
指令吗?
Q1: Do I need write my own custom ngControl
directive?
Q2:如何将ngControl
传播到由<inputCustom>
包裹的内部<input>
元素?
Q2: How to propagate ngControl
to the inner <input>
element wrapped by <inputCustom>
?
Q3:我应该如何在周围的表格ControlGroup
中注册我的Control
?
Q3: How should I register my Control
inside the surrounding forms ControlGroup
?
推荐答案
我看到两种实现方法:
-
提供控件作为自定义组件的参数:
@Component({
selector: 'inputCustom',
template: `
<input [ngFormControl]="control"/>
`
export class FormFieldComponent {
(...)
@Input()
control: Control;
}
这样,您的输入将自动采用父组件中定义的表单的一部分.
This way your input will automatically takes part of the form defined in the parent component.
实施兼容ngModel的组件.实现的时间更长(您需要在自定义指令中实现并注册ControlValueAccessor
),但是通过这种方式,您将可以直接在自定义组件上使用ngFormControl
和ngModel
.
Implement an ngModel-compliant component. It's a bit longer to implement (you need to implement and register a ControlValueAccessor
within a custom directive) but this way you will be able to use directly the ngFormControl
and ngModel
directly on your custom component.
<inputCustom type ="email" [ngFormControl]="email">
有关更多详细信息,请参见此问题: Angular 2自定义表单输入
See this question for more details: Angular 2 custom form input
我认为这篇文章可能会让您感兴趣:
I think that this article could interest you:
- 实现Angular2表单–超越基础(第2部分)- http://restlet.com/blog/2016/02/17/implementing-angular2-forms-beyond-basics-part-2/
这篇关于将angular2表单指令应用于自定义输入表单元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!