在我的应用程序中,我尝试放置一个按钮,显示/隐藏带有布尔组件属性的输入字段.如果按钮显示输入,则应在输入上设置焦点.但它似乎不起作用.如果我删除* 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',[]); }); } }
EventEmitters用于输出,不用于输入.尝试这样的事情:
@Directive({ selector: '[focus]' }) export class FocusDirective implements OnChanges { @Input('focus') focus: boolean; constructor(private elementRef : ElementRef,private renderer : Renderer ) { } ngOnChanges() { if (this.focus) { this.renderer .invokeElementMethod(this.elementRef.nativeElement,[]); } } }