Search code examples
angularangular2-templateangular2-directives

How to implement ngModel on custom elements?


Given a simple input element I can do this:

<input [(ngModel)]="name" /> {{ name }}

This doesn't work for my custom elements:

<my-selfmade-combobox [(ngModel)]="name" values="getValues()" required></my-selfmade-combobox>

How can I implement it?


Solution

  • If you really need [(ngModel)] (which supports ngForm, unlike [(myProp)] approach), I think this link will answer your question:

    We need to implement two things to achieve that:

    • A component that provides the logic of your form component. It doesn't need an input since that will be provided by ngModel itself
    • A custom ControlValueAccessor that will implement the bridge between this component and ngModel / ngControl

    The previous link gives you a complete sample...