Home > Mobile >  how to avoid changing of ng bootstrap dropdown when enter key is pressed on any on input field in an
how to avoid changing of ng bootstrap dropdown when enter key is pressed on any on input field in an

Time:07-08

i am using angular powered bootstrap dropdown and here whenever i do enter key press in input, it always changes the dropdown value to first option.

DEMO LINK

HTML:

<div >
          <div >
            <div ngbDropdown >
              <button
                type="button"
                
                id="dropdownBasic1"
                ngbDropdownToggle
              >
                {{ clickMessage }}
              </button>
              <div ngbDropdownMenu aria-labelledby="dropdownBasic1">
                <button
                  ngbDropdownItem
                  
                  href="#"
                  (click)="getText($event.target.innerText)"
                >
                  Option 1
                </button>
                <button
                  ngbDropdownItem
                  
                  href="#"
                  (click)="getText($event.target.innerText)"
                >
                  Option 2
                </button>
                <button
                  ngbDropdownItem
                  
                  href="#"
                  (click)="getText($event.target.innerText)"
                >
                  Option 3
                </button>
              </div>
            </div>
          </div>
        </div>

TS:

  clickMessage = 'Choose an option';

  getText(text) {
    this.clickMessage = text;
  }

CodePudding user response:

The behaviour you are seeing is due to you have some buttons without any type attribute and by default the buttons in the form trigger the submit event.Add the type to the buttons in the dropdown and it should work.

<div ngbDropdownMenu aria-labelledby="dropdownBasic1">
    <button
        type="button"
        ngbDropdownItem
        
        href="#"
        (click)="getText($event, $event.target.innerText)"
    >
        Option 1
    </button>
    <button
        type="button"
        ngbDropdownItem
        
        href="#"
        (click)="getText($event, $event.target.innerText)"
    >
        Option 2
    </button>
    <button
        ngbDropdownItem
        
        href="#"
        (click)="getText($event, $event.target.innerText)"
    >
        Option 3
    </button>
</div>

CodePudding user response:

Add the following code to your ts file.

  @HostListener('keydown', ['$event']) public onKeyDown(evt) {
    if (evt.key === 'Enter') {
      evt.preventDefault();
      this.onSubmit();
    }
  }

I write it for you in the following stackblitz.

https://stackblitz.com/edit/angular12-bootstrap-skiant?file=src/app/app.component.ts,src/app/app.component.html,src/app/app.module.ts

  • Related