所以我有一个输入:
<input id='search'placeholder="Search" formControlName='search'
(click)="toggleDropDown()" type='text' novalidate>
当您点击它时,它会显示一个“下拉菜单”:
<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>
这是TypeScript:
showDropDown = false;
toggleDropDown() {
this.showDropDown = !this.showDropDown;
console.log('clicked');
}
当用户点击输入时,下拉菜单会显示在屏幕上的DOM /中。到目前为止,我只能通过点击输入本身关闭下拉列表,但我试图通过点击其他地方找到关闭菜单的方法。
答案 0 :(得分:3)
参考blur
:Angular 2 on blur
符合这一点:
<input id='search'placeholder="Search" formControlName='search'
(click)="toggleDropDown()" (blur)="closeDropDown()" type='text' novalidate>
TS:
closeDropDown() {
this.showDropDown = false;
console.log('clicked outside');
}
答案 1 :(得分:1)
您可以执行以下操作:
1)在“ @Component”装饰器中添加主机:
host: {
"(window:click)": "onDropClick()"
}
2)添加您在主机上调用的函数:
onDropClick() { // close drop down
this.YOUR-DROP-DOWN-NAME = false;
}
3)停止传播您的放置事件:
onSearchDrop(event) { // YOUR DROP DOWN FUNCTION
event.stopPropagation(); // Drop down propagation
}
示例:
@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;
}
}