Home > other >  Apply directive to input field using a click event
Apply directive to input field using a click event

Time:08-18

I am trying to apply my keyboard directive using a method in my TS file. I have a button that has the method attached to it in which I call the directive but I do not see anything happening.

I created a stackblitz for it https://stackblitz.com/edit/onscreen-keyboard-ztv1n1?file=src/app/app.component.ts

Here is my code as well

TS

isKeyboardActive() {
  this.appOskInput;
}

HTML

<div>
  <label>Name</label>
  <input appOskInput  />
</div>
<div>
  <label>Cell</label>
  <input appOskInput type="text" />
</div>

<button (click)="isKeyboardActive()">Enable</button>

<app-keyboard></app-keyboard>

Directive (separate file)

@Directive({
  selector: "[appOskInput]"
})
...

So basically when I click the isKeyboardActive button I want to append appOskInput to the first input field Name

The reason why I want to do this is because the keyboard only opens when I click within the input field which is not a good user experience

CodePudding user response:

First expose KeyboardService and ElementRef as public properties in directive

  public el:ElementRef;
  public keyboard:KeyboardService;

  constructor( _el: ElementRef,  _keyboard: KeyboardService) {
    this.el = _el;
    this.keyboard = _keyboard;
  }

Then inside component when you click button you can enable and disable keyboard as per your requirement.

isKeyboardActive() {  
    this.appOskInput.first.keyboard.fireKeyboardRequested(true);
    this.appOskInput.first.el.nativeElement.focus();
  }

Forked Working Example

  • Related