Search code examples
angularangular-reactive-formsangular-ngmodelform-control

How to add an ngModel and formControlName together in an angular custom component?


I want to make a custom component in angular .Sometimes i will use recative forms to call this component and sometimes without reactive components.

For that ,sometimes i will use formControlName and sometimes ngmodel. The problem is that i can not add those two properties together in my custom component.

https://stackblitz.com/edit/ng-tie-reactive-forms-throgh-wrapper-hfptmu?file=src%2Fapp%2Fdate-wrapper%2Fdate-wrapper.component.html

ngmodel and custom component together


Solution

  • So what you're looking for is the ControlValueAccessor interface: https://angular.io/api/forms/ControlValueAccessor

    If you implement this interface on your component, the methods of the interface will allow the component to work with both template driven and reactive forms (ngModel and formControl/formControlName). For clarity, you don't need ngModel or formControlName as Inputs on your component, this interface will cause this to be allowed.