Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Apply directive to input field using a click event

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading