【发布时间】:2018-04-14 07:47:00
【问题描述】:
我已经实现了一个非常简单的材质自动完成。
并使用 Angular 5,通过 bootstrap 4 下拉菜单显示表单
我发现当我将自动完成功能放入下拉列表并选择其中的一个项目进行自动完成时,它会关闭整个下拉列表。
自动完成本身,按预期工作
HTML:
<div class="btn-filter">
<button class="btn" id="user-filter" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">Filter <span class="ion-levels"></span></button>
<div class="dropdown-menu" id='dClose' aria-labelledby="user-filter" style="width: 400px; height: 300px">
<form class="example-form">
<mat-form-field class="example-full-width">
<input matInput placeholder="State" aria-label="State" [matAutocomplete]="auto" [formControl]="stateCtrl">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let state of filteredStates | async" [value]="state.name">
<img style="vertical-align:middle;" aria-hidden src="{{state.flag}}" height="25" />
<span>{{ state.name }}</span> |
<small>Population: {{state.population}}</small>
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
</div>
Typescript/Javascript,用于自动完成:
constructor() {
this.stateCtrl = new FormControl();
this.filteredStates = this.stateCtrl.valueChanges
.pipe(
startWith(''),
map(state => state ? this.filterStates(state) : this.states.slice())
);
}
filterStates(name: string) {
return this.states.filter(state =>
state.name.toLowerCase().indexOf(name.toLowerCase()) === 0);
}
这仅用于测试目的,我不知道最佳实践,但我在 ngAfterViewInit 中设置了超时
ngAfterViewInit() {
setTimeout(()=>{
document.getElementById('dClose').addEventListener('click', (e)=>{
e.stopImmediatePropagation();
});//this works, when the actual dropdown itself is clicked it does not close
document.getElementById('dClose').addEventListener('onblur', (e)=>{
e.stopImmediatePropagation();
});//this does not work, when the autocomplete is selected, the dropdown closes
}, 3000)
}
感谢任何想法
【问题讨论】:
-
你能添加你的代码吗?
-
选择元素的自动完成属性是无效的 HTML (w3.org/TR/2012/WD-html-markup-20120320/select.html#select)
-
感谢您的回复我已经更新了问题,这应该可以更清楚地说明情况,如果您希望我提供完整的代码,请告诉我
标签: javascript angular bootstrap-4 angular-material