I am trying to get the native element value in Angular 10 but am getting an undefined
instead
@Directive({
selector: "[appOskInput]"
})
constructor(private el: ElementRef) {}
private onKey(key: string) {
let element = this.el.nativeElement,
console.log("element: " element.value);
}
<form-input
appOskInput
[data]="{
formControlName: 'firstName',
name: 'firstName'
}">
</form-input>
Any idea what I can do?
CodePudding user response:
Try it like that:
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({ selector: '[testDirective]' })
export class TestDirective {
constructor(private el: ElementRef) {
let element = this.el.nativeElement;
console.log(element);
}
@HostListener('keyup') KeyUp() {
let element = this.el.nativeElement;
console.log(element);
}
}
You can try it out here: https://stackblitz.com/edit/angular-n4mq7a?file=src/app/directives/test.directive.ts
You need to open console in the right window (on the bottom is a "console" button)
CodePudding user response:
You are forgetting to bind the keyup or down event with your function. Below code will help you.
@HostListener('keyup')
public onKey() {
let element = this.el.nativeElement;
console.log(element.value);
}