I'm creating web components for a project. I'd love to make those web components behave in forms like native elements in Angular : that automatically, [(ngModel)]
and / or [FormControl]
works on them.
I thought that was impossible because of the type of the events fired by my web-component. Those are DOM Events that only accept a custom value in the detail
field, and Angular only checks the value
field. So I wrapped up my web-components into an Angular component which implemented the ngValueAccessor
API.
But now that I think of it, native element like input
does communicate well with Angular API even though they are native and, I assume, use the same event type as my web-component.
How so ?
CodePudding user response:
Angular uses default class implementations for the native elements: https://angular.io/api/forms/ControlValueAccessor#class-implementations
An input
uses the DefaultValueAccessor. It also has a ngDefaultControl
selector.
This value accessor is used by default for
<input type="text">
and<textarea>
elements, but you could also use it for custom components that have similar behavior and do not require special processing. In order to attach the default value accessor to a custom element, add the ngDefaultControl attribute as shown below.
<custom-input-component ngDefaultControl [(ngModel)]="value"></custom-input-component>