我提到了this other walk through,但我无法准确理解它是如何运作的。我已将此添加到我的ts文件中:
@Component({
host: {
'(document:click)': 'onOutsideClick($event)',
},
})
class SomeComponent() {
constructor(private _eref: ElementRef) { }
onOutsideClick(event) {
console.log('click')
if(!this._eref.nativeElement.contains(event.target)){
this.companyResults = null;
}
}
并希望将其应用于HTML中的这个下拉列表,其中有人在外部点击时将ul数据设置为null。
<input id="positionCompanyName" name="companyName_{{i}}" class="search-input"
[(ngModel)]="candidate.positions[i].company_name"
(keyup)="$event.target.value && searchCompany$.next($event.target.value)">
<ul class="search-dropdown-ul" *ngIf="companyResults && positionIndex === i">
<a class="search-dropdown-div" *ngFor="let companyResult of companyResults" (click)="addCompany(companyResult, i)">
<li class="search-dropdown-li">
{{ companyResult.name }
</li>
</a>
</ul>
答案 0 :(得分:1)
ElementRef(在构造函数中)为您提供对组件本身的本机元素(DOM元素)的引用。
if(!this._eref.nativeElement.contains(event.target)){
}
此部分检查您是否点击了组件的任何部分,这不是您想要的。您可以使用@ViewChild检查是否点击了search-dropdown-ul 因此,在HTML中,您声明某些内容是ViewChild
<ul #list class="search-dropdown-ul" *ngIf="companyResults && positionIndex === i">
注意#list。 现在在组件中,您可以通过说
来引用它 @ViewChild('list') list: ElementRef;
最后,你看它是否被点击了:
if(!this.list.nativeElement.contains(event.target)){
//do your thing here
}