4

I want to create a custom InputCustom component and use it to create model-driven forms.

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{....}

In Angular2 when you create a model-driven form

<form [ngFormModel]="formRef">
    <input type ="email" ngControl="email">
</form>

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: Do I need write my own custom ngControl directive?

Q2: How to propagate ngControl to the inner <input> element wrapped by <inputCustom>?

Q3: How should I register my Control inside the surrounding forms ControlGroup?

4

3 回答 3

3

我看到了两种实现方式:

  • 提供您的控件作为自定义组件的参数:

    @Component({
      selector: 'inputCustom',
      template: `
        <input [ngFormControl]="control"/>
      `
    export class FormFieldComponent {
      (...)
      @Input()
      control: Control;
    }
    

    这样,您的输入将自动采用父组件中定义的表单的一部分。

  • 实现一个符合 ngModel 的组件。实现的时间要长一些(您需要ControlValueAccessor在自定义指令中实现和注册 a ),但是这样您就可以直接在自定义组件上使用ngFormControland 。ngModel

    <inputCustom type ="email" [ngFormControl]="email">
    

    有关更多详细信息,请参阅此问题:Angular 2 custom form input

我认为这篇文章可能会让您感兴趣:

于 2016-02-26T09:10:08.773 回答
2

我想自定义 ValueAccessor 应该可以。

请参阅
- https://plnkr.co/edit/Bz7wLC5qq7s6Fph1UwpC?p=preview(DI提供的值访问器)

    providers: [provide(NG_VALUE_ACCESSOR, {useClass: UIDropdownComp, multi: true})]
})
export class UIDropdownComp implements ControlValueAccessor {

- http://plnkr.co/edit/slVMz6Kgv6KlnUNMDe3o?p=preview(ngControl 注入组件和“手动”分配的值访问器

export class Address implements ControlValueAccessor{
addressForm: ControlGroup;
    value:any;
     addressForm: ControlGroup;
  constructor(@Optional() ngControl: NgControl, elementRef: ElementRef,fb: FormBuilder) {  
    ngControl.valueAccessor = this;

另见https://github.com/angular/angular/issues/2543

于 2016-02-26T09:12:37.480 回答
0

实现自定义输入表单元素的 Angular 2 材料是了解如何实现 ValueAccessor 的重要信息来源。

因此,只需深入这里的源代码并查看输入组件: https ://github.com/angular/material2

于 2016-05-30T19:36:27.297 回答