網站搜尋

angular - 來自共享模組的指令不可見


嘗試深入學習 Angular 2,有一些 Angular 1 的經驗,並且有一些疑惑。

我做了一個共享模組:

import { NgModule }      from '@angular/core';
import { CommonModule }        from '@angular/common';

import { Constants }   from './injectables/constants';
import { Utils } from "./injectables/utils";
import { HighlightDirective } from "./directives/highlight";

@NgModule({
    imports: [ CommonModule ],
    declarations: [ HighlightDirective ],
    providers: [ Constants, Utils ],
    exports: [ HighlightDirective ]
})
export class VCommonModule { }

請糾正我如果我錯了,但據我所理解,這裡只有指令、管道和組件需要導出?服務(可注入的)在我將這個模組加入到我的 AppModule 的 imports 後就可以直接使用了?所以我這麼做了:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { VCommonModule } from './common/module';
import { FormsModule } from "@angular/forms";

import { AppComponent }   from './faq/components/app';
import { SearchComponent }   from './faq/components/search';
import { ArticleComponent } from "./faq/components/article";
import { TopResultsComponent } from "./faq/components/topResults";
import { AjaxService } from "./faq/injectables/ajaxService";
import './rxjs-operators';

@NgModule({
    imports:      [ BrowserModule, FormsModule, HttpModule, VCommonModule ],
    declarations: [ AppComponent, SearchComponent, ArticleComponent, TopResultsComponent ],
    providers: [ AjaxService ],
    bootstrap:    [ AppComponent ]
})

export class AppModule { }

但是當我嘗試在我的組件中使用 [highlight] 指令,在 AppModule 中,它顯示我一個錯誤

zone.js:388 Unhandled Promise rejection: Template parse errors:
Can't bind to 'highlight' since it isn't a known property of 'span'. ("         <br/>
                <span [innerHTML]="article.Content__c"
                      [ERROR ->][highlight]
                      keywords="test"></span> <!-- [innerHTML]="article.Content__c | "): SearchComponent@39:26 ; Zone: <root> ; Task: Promise.then ; Value: Error: 

在我將它們作為我的元件的 providers: [ Constants, Utils ] 添加後,來自 VCommonModule 的服務似乎運作正常

import {Directive, Input, ElementRef, Renderer, OnChanges} from "@angular/core";

@Directive({
    selector: '[highlight]'
})
export class HighlightDirective implements OnChanges{
    @Input()
    keywords:string;

    highlightClass: string = 'highLight';

    constructor(
        private elementRef:ElementRef,
        private renderer:Renderer) {
    }

    replacer(match, item) {
        return `<span class="${this.highlightClass}">${match}</span>`;
    }

    tokenize(keywords) {
        keywords = keywords.replace(new RegExp(',$','g'), '').split(',');
        return keywords.map((keyword) => {
            return '\\b'+keyword.replace(new RegExp('^ | $','g'),     '')+'\\b';
        });
    }

    ngOnChanges() {
        if (this.keywords) {
            var tokenized = this.tokenize(this.keywords);
            var regex = new RegExp(tokenized.join('|'), 'gmi');

            var html =     this.elementRef.nativeElement.innerHTML.replace(regex, (match, item) => {
                return this.replacer(match, item);
            });

            this.renderer.setElementProperty(this.elementRef.nativeElement,     'innerHTML', html);
        }
    }
}

附註:Angular 版本 2.1.2

答案#1

你的問題不是出在模組上,而是模板中使用的語法。

根據錯誤訊息,你使用了一向綁定語法——因為你的 highlight 指令被大括號包裹著:

<span ... [highlight] ...></span>

在這種情況下,Angular 會嘗試綁定到指令屬性或元素屬性。你的指令沒有名為 highlight 的輸入屬性,且 span 元素也沒有 highlight 屬性,因此會產生錯誤。

如果你移除大括號,問題應該會解決:

<span ... highlight ...></span>