我试图让一个html Select元素(组件X的子元素)显示和隐藏,以响应该组件X上的焦点和模糊事件。 在组件X上,我尝试使用以下方法设置侦听器: this.elementRef.nativeElement.addEventListener('focus',myFunc)
但是不起作用。因此,我目前正在尝试使用this.renderer.listen,但两者都不起作用。这是组件TS和模板:
Component.ts
import { Component, ContentChild, ElementRef, Renderer2, AfterViewInit, OnDestroy } from '@angular/core';
import { InputRefDirective } from '../input-ref/input-ref.directive';
@Component({
selector: 'input-with-suggestion',
templateUrl: './input-with-suggestion.component.html',
styleUrls: ['./input-with-suggestion.component.css']
})
export class InputWithSuggestionComponent implements AfterViewInit, OnDestroy {
@ContentChild(InputRefDirective)
inputRef: InputRefDirective;
hiddenSuggestions = false;
focusListener: () => void;
blurListener: () => void;
constructor(private elementRef: ElementRef, private renderer: Renderer2) {
}
ngAfterViewInit() {
this.blurListener = this.renderer.listen(this.elementRef.nativeElement, 'blur', this.hideSuggestions.bind(this) );
this.focusListener = this.renderer.listen(this.elementRef.nativeElement, 'focus', this.showSuggestions.bind(this) );
}
ngOnDestroy() {
this.blurListener();
this.focusListener();
}
hideSuggestions(): void {
console.log('hide');
this.hiddenSuggestions = true;
}
showSuggestions(): void {
console.log('show');
this.hiddenSuggestions = false;
}
get suggestions() {
return this.inputRef.data;
}
}
和component.html:
<ng-content></ng-content>
<select *ngIf="(suggestions.length > 0) && !hiddenSuggestions" [size]="suggestions.length" style="color: black; position: absolute; display: block; width: auto; overflow: hidden" multiple>
<option *ngFor="let suggestion of suggestions" value="suggestion.value">
{{suggestion.text}}
</option>
</select>
我缺少明显的东西吗? 似乎HostListener不能与@Component一起使用,而只能与@Directive一起使用。我也是这样吗?
谢谢!
答案 0 :(得分:0)
InputWithSuggestionComponent实例不可访问,其内容(因此为输入)被奇怪地隐藏了。将监听器设置为nativeElement.querySelector('input'),而不是nativeElement对其进行固定。