0

I have one input box. I am showing some value in it. I want to make that input box as read-only. But arrows key, Home key, End key these keys should work.

I am showing multiple URLs by comma separated way. I want to navigate between these URLs. That's why I need above keys should work.

I tried with [readonly]="true", but I cant navigate within input box. I can not use disabled as well.

<input matInput placeholder="Enter Promotional Link URL"  [(ngModel)]="lms.LmPromotionalUrl" name="LmPromotionalUrl">

output

www.facebook.com,www.google.com,www.cisco.com

Is there any way to achieve this behaviour?

3
  • 1
    May I specify something? As I understood your input is too small to show the whole content of it ? Probably if that is the problem, you may just forbid all keys using JS and allow just those you mentioned Commented Jun 13, 2018 at 10:20
  • @Sh.Pavel I had tried keyup and keydown events as well. It works when the input box is empty. But when data is present then this is not working. Commented Jun 13, 2018 at 10:23
  • hmm..it's wierd..maybe the good point would be to add some check on the content length ? Like if there is length > 0 then would be check on the keyup/keydown events? But i'm not sure if this would work.. I had never applied it to disabled input. Commented Jun 13, 2018 at 10:28

1 Answer 1

1

Here's a solution in plain javascript, you can simply adapt that to a HostListener or (keydown) in angular. Basically we're just returning false and preventing default behavior for any key that is not the arrow keys (I'm using a mac and don't know which home key is, you can check that here and add it to the array of allowed keycodes

document.getElementById('foo').addEventListener('keydown', e => {
  if (![37, 38, 39, 40].includes(e.keyCode)) {
    e.preventDefault();
    return false;
  }

})
<input id="foo" placeholder="Enter Promotional Link URL" name="LmPromotionalUrl" value="foo">

In the example you can still "navigate" through the values using arrow keys, but can't type or delete anything.

Sign up to request clarification or add additional context in comments.

6 Comments

my value (lms.LmPromotionalUrl) is an array of URLs. when I am trying to push new URL into that array. It giving me an error. Because array getting converted into the string.
Feel free to ask a new question if you have a different one @KaustubhKhare
I did changes as you suggested, but when I am passing data to value, it is converting the array into the string and I am getting the error while adding new URL for unshift method.
Like written in the answer, you need to adapt the code to angular. You'd set the data just like you did before, not with value @KaustubhKhare
I tried. It works when the input box is empty. But when data is present then this is not working.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.