Ivar Reukers
Ivar Reukers

Reputation: 7729

Disable input when enter is pressed dynamically

I'm making a website where there will be a lot of input fields. Sort of like a scanner, I would like to disable each input when the enter is pressed.

I now have this:

<input (keyup.enter)="doSomething()"/>

But I would want to pass along the input itself so I can disable these inputs. (f.e. something like: doSomething(input) { input.attr.disabled = true; }

How can I get this input field in my doSomething function?

Note: I do not want to use something like <input #input ... since I have so many input fields. This will only create a lot of work.

All I want is that each time the enter is pressed in an input field, that it gets disabled (using only one function for all).

Upvotes: 3

Views: 1672

Answers (3)

Vinay
Vinay

Reputation: 962

Also you can try something like this,

<input id="reply" name="reply" onKeyPress="enterpressalert(event)"/>

<script>
function enterpressalert(e){
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) { //Enter keycode
 e.target.disabled = true;
}
}
</script>

Upvotes: 1

Teddy Sterne
Teddy Sterne

Reputation: 14201

Create a directive that listens for the keyup.enter on the input and then sets the disabled attribute on the input. This can be done with a directive like this:

@Directive({
  selector: 'input[disable-on-enter]',
})
export class DisableOnEnterDirective {
  @HostBinding('attr.disabled') isDisabled;
  @HostListener('keyup.enter') disableInput() {
   this.isDisabled = true ;
  }
}

And it can be used like this:

<input disable-on-enter placeholder="Press enter to disable" />

Demo

Upvotes: 5

willmaz
willmaz

Reputation: 2475

You can do this :

<input (keyup.enter)="doSomething($event)"/>

doSomething(event) {  event.target.disabled = true; }

Upvotes: 1

Related Questions