Reputation: 968
I've got an input field that I have attached a directive to.
<input type="email"
id="email"
formControlName="email"
email
[placeholder]>
The directive is placeholder, when a user updates the input with a new value I want to run some code in the directive:
@Input() public input: String;
constructor(private el: ElementRef) {}
@HostListener('change') ngOnChanges() {
console.log('test');
}
I thought I'd need to use the hostListener directive to check for a change but this isn't working as I intended. My intention is to add a class when the input has a value inside of it.
What do others do to achieve this?
Upvotes: 1
Views: 7918
Reputation: 318
You can use de OnChange
@Directive({
selector: '[my-directive]'
})
export class MyDirective implements OnChanges {
@Input('value-listen') public formControl: any;
ngOnChanges(changes: SimpleChanges){
console.log(changes);
}
}
Only should pass the formControl in [value-listen]="yourValue"
Upvotes: 0
Reputation: 27303
Use Template Driven Form and Define input property binding as below in your template
<input type="email"
id="email"
[(ngModel)]="email"
[input]="email"
placeholder>
Directive.ts
@Input() public input: String;
constructor(private el: ElementRef) {}
@HostListener('change') ngOnChanges() {
console.log('test');
}
it might help and also check this example https://stackblitz.com/edit/angular-na4ncb?file=app%2Fapp.component.html
Upvotes: 1