簡體   English   中英

沒有Modal Angular2的提供者

[英]No provider for the Modal Angular2

我試圖在指令的構造函數中使用可選參數但由於錯誤“沒有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)當沒有模態,並且指令附加到元素時,該元素應該只獲得焦點。

實際上,您可以簡單地使用Angular方式定義Optional參數。 現在?:是用於定義可選參數的打字稿方式。

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

private modal: Modal前面添加@Optional() private modal: Modal

並檢查this.modal是否為真,即

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

這應該可以解決問題。 希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM