简体   繁体   English

没有Modal Angular2的提供者

[英]No provider for the Modal Angular2

I'm trying to use optional parameters here in the constructor of the directive but have been unsuccessful all the times because of the error "No provider for Modal". 我试图在指令的构造函数中使用可选参数但由于错误“没有Modal的提供者”而一直都不成功。

I have a Modal class with a component and I am subscribing to the modal.shown() to focus in my directive. 我有一个带有组件的Modal类,我订阅了modal.shown()以专注于我的指令。 Now, I want to use the same directive to even force focus on some other elements. 现在,我想使用相同的指令甚至强制关注其他一些元素。 So, I planned to use the optional arguments for the modal so that it works only when the constructor is passed that argument. 因此,我计划使用模态的可选参数,以便仅在构造函数传递该参数时才起作用。

I did the following: 我做了以下事情:

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();
    }

}

This works great in the case of the Modal ie, when I use the directive tabFocus to the html element of the modal, the focus goes there perfectly. 这在Modal的情况下效果很好,即,当我使用指令tabFocus到模态的html元素时,焦点完美地存在。 But whenever I use the directive for an another button element, the code breaks and I get the error "No Provider for Modal". 但每当我将该指令用于另一个按钮元素时,代码就会中断并且我得到错误“没有Modal的提供者”。

What I want to achieve in simple words is: I want to be able to use the same directive for two different purposes. 我想用简单的语言实现的目标是:我希望能够将同一指令用于两个不同的目的。 1) When there is a modal, the element on the modal should get the focus. 1)当有模态时,模态上的元素应该得到焦点。 2) When there is no modal, and the directive is attached to an element, that element should just get the focus. 2)当没有模态,并且指令附加到元素时,该元素应该只获得焦点。

Actually, you could simply use the Angular Way of defining the Optional arguments. 实际上,您可以简单地使用Angular方式定义Optional参数。 Right now ?: is typescript way of defining optional arguments. 现在?:是用于定义可选参数的打字稿方式。

import { Optional } from "@angular/core";

Add @Optional() in front of the private modal: Modal private modal: Modal前面添加@Optional() private modal: Modal

and check if this.modal is true ie, 并检查this.modal是否为真,即

if(this.modal){
 //do something.
}

This should do the trick. 这应该可以解决问题。 Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM