我试图在指令的构造函数中使用可选参数但由于错误“没有Modal的提供者”而一直都不成功.
我有一个带有组件的Modal类,我订阅了modal.shown()以专注于我的指令.现在,我想使用相同的指令甚至强制关注其他一些元素.因此,我计划使用模态的可选参数,以便仅在构造函数传递该参数时才起作用.
我做了以下事情:
import { Directive,ElementRef,OnDestroy } from "@angular/core"; import { Subscription } from 'rxjs/Rx'; import { Modal } from "./modal"; import * as ng from "@angular/core"; import { Inject } from "@angular/core"; @Directive({ selector: "[tabFocus]" }) export class Focus implements ng.OnDestroy,ng.OnInit { private _subscription: Subscription; constructor(private _el: ng.ElementRef,@Inject(Modal) private modal?: Modal) { if (this.modal != undefined) { this._subscription = this.modal.shown.subscribe(() => this._el.nativeElement.focus()); } } ngOnInit() { this._el.nativeElement.focus(); } ngOnDestroy() { this._subscription.unsubscribe(); } }
这在Modal的情况下效果很好,即,当我使用指令tabFocus到模态的html元素时,焦点完美地存在.但每当我将该指令用于另一个按钮元素时,代码就会中断并且我得到错误“没有Modal的提供者”.
我想用简单的语言实现的目标是:我希望能够将同一指令用于两个不同的目的. 1)当有模态时,模态上的元素应该得到焦点. 2)当没有模态,并且指令附加到元素时,该元素应该只是获得焦点.