我创建了一个显示我的意思的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',[]); }); } }