简体   繁体   中英

Close Dropdown menu by clicking outside of it (Angular 4)

So I have an input:

<input id='search'placeholder="Search" formControlName='search'
       (click)="toggleDropDown()" type='text' novalidate>

when you click on it, it shows a "dropdown" menu:

<div *ngIf="showDropDown"
           class="search-bar-results">
        <li
          *ngFor="let x of searchItems | filter: getSearchValue()"
          (click)="selectValue(artist)">
            <img src="{{x.image}}"
                 alt="search result artist image"
                 class="search-bar-image">
            <p>{{x.name}}</p>
            <p>{{x.type}}</p>
        </li>
      </div>

Here is the TypeScript:

showDropDown = false;

toggleDropDown() {
    this.showDropDown = !this.showDropDown;
    console.log('clicked');
  }

When a user clicks on the input, the dropdown appears in the DOM / on the screen. So far I can only close the dropdown by clicking on the input itself, but I am trying to find a way to close the menu by clicking elsewhere.

Referring to blur : Angular 2 on blur

Something in line with this:

<input id='search'placeholder="Search" formControlName='search'
   (click)="toggleDropDown()" (blur)="closeDropDown()" type='text' novalidate>

TS:

closeDropDown() {
    this.showDropDown = false;
    console.log('clicked outside');
}

you can do the following:

1) add host in your "@Component" decorator:

  host: {
    "(window:click)": "onDropClick()"
  }

2) add function that you called on host:

  onDropClick() { // close drop down
    this.YOUR-DROP-DOWN-NAME = false;
  }

3) Stop propagation of your drop event:

  onSearchDrop(event) { // YOUR DROP DOWN FUNCTION
    event.stopPropagation(); // Drop down propagation
  }

example:

@Component({
  selector: 'app-search-page',
  templateUrl: './search-page.component.html',
  styleUrls: ['./search-page.component.scss'],

  host: {
    "(window:click)": "onDropClick()"
  }

})
export class SearchPageComponent implements OnInit {
  searchDrop = false;

  constructor() { }

  ngOnInit() {
  }

  onSearchDrop(event) {
    this.searchDrop = true;
    this.modalDrop = false;

    event.stopPropagation(); // Drop down propagation
  }


  onDropClick() { // close drop down
    this.searchDrop = false;
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM