在我的應用程序中,我試圖放置一個按鈕,顯示/隱藏一個布爾組件屬性的輸入字段。如果按鈕顯示輸入,則應在輸入上設置焦點。但它似乎不工作。如果我刪除*ngIf
焦點指令工作正常。Angular2使用* ngIf與焦點指令?
我創建了plunker,顯示了我的意思。描述我的「問題」很難。
HTML組分
<input *ngIf="filterShow.options"
[focus]="filterFocus.options"
[(ngModel)]="filter.options">
<button type="button"
(click)="setShowFilter('options')">
focus
</button>
setShowFilter()函數
private setShowFilter(filter: string) {
this.filterShow[filter] = !this.filterShow[filter];
/* reset filter */
this.filter[filter] = "";
this.filterFocus[filter].emit(true);
}
focus.directive.ts
@Directive({
selector: '[focus]'
})
export class FocusDirective implements OnInit {
@Input('focus') focusEvent: EventEmitter<boolean>;
constructor(private elementRef : ElementRef,
private renderer : Renderer ) { }
ngOnInit() {
this.focusEvent.subscribe(event => {
this.renderer
.invokeElementMethod(this.elementRef.nativeElement, 'focus', []);
});
}
}
您正在使用事件發射器錯誤。他們是爲了孩子 - >父母的溝通,而不是爲了父母 - >孩子。我發佈的內容適用於我:https://plnkr.co/edit/YtaRtA0e5L6ewxq7uCH9?p=preview – adharris
'Renderer'和它的'.invokeElementMethod()'方法在此時已被棄用。現在可以直接調用'this.elementRef.nativeElement.focus()'。 –