Applying angular2 form directives to custom input form elements

百般思念 提交于 2019-12-05 14:34:57
Thierry Templier

I see two ways to implement that:

  • Provide your control as parameter of your custom component:

    @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.

  • 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">
    

    See this question for more details: Angular 2 custom form input

I think that this article could interest you:

I guess a custom ValueAccessor should do.

See
- https://plnkr.co/edit/Bz7wLC5qq7s6Fph1UwpC?p=preview (value accessor provided by DI)

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

- http://plnkr.co/edit/slVMz6Kgv6KlnUNMDe3o?p=preview (ngControl injected into the component and value accessor assigned "manually"

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

See also https://github.com/angular/angular/issues/2543

Angular 2 material which implements custom input form element is a great source of information to see how to implement ValueAccessor.

So just dive in the source code here and have a look at the input component : https://github.com/angular/material2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!