Let's say I'm writing a custom attribute directive for use on Angular2 form elements. I want to be able to use my attribute like so:
<form [formGroup]="myFormGroup">
<input type="text" [myHighlight] formControlName="name" />
</form>
Inside my directive I have something like this:
@Directive({selector: '[myHighlight]'})
export class MyHighlightDirective {
constructor (private el: ElementRef) {
this.el.nativeElement.style.backgroundColor = 'yellow';
}
};
But now let's say I want to do something on all changes to the input control. Maybe I want to randomize the color on each change.
The HostListener('onChange')
event from the Angular2 guide works when the user is typing into the input box. But it doesn't get activated for setValue
events that are called on the form control, even with emitEvent
set to true. The Angular docs on Forms say that setValue
will cause a valueChanges
event to be emitted on the form control object. But I don't want to have to pass this in to the directive every time I use it, as that's clunky.
Is there any other way for the directive to get access to the original form control, given that it just has the element reference?
No provider for FormControl!
when I do that and I haveFormsModule
imported into my module. When I addFormControl
to theproviders
part of my module, I getSyntax error Can't resolve all parameters for FormControl: (?, ?, ?). at SyntaxError.BaseError
– Headlight