Visibility issue with directive in shared module

Exploring the world of Angular 2 after having some hands-on experience with Angular 1 and encountering a few challenges.

I've created a shared module:

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 { }

If I understood correctly, only directives, pipes, and components need to be exported in this module. Services (Injectables) can be used directly after including this module in the imports of my AppModule. So, that's exactly what I did:

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 { }

However, when attempting to use the [highlight] directive within my component inside AppModule, an error is displayed.

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: 

The services from VCommonModule seem to work fine after adding them as providers: [ Constants, Utils ] in my component.

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

PS: angular version 2.1.2

Answer №1

It seems that the issue lies in the syntax used within your template, rather than with any modules.

The error message indicates that you have mistakenly employed the one-way binding syntax by enclosing your highlight directive in curly braces:

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

In this case, Angular will try to bind to a directive or element property named highlight, which leads to an error as there is no such input property for your directive and the span element does not have a highlight property.

To resolve this issue, simply remove the curly braces from around the directive:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Installation of Angular-cli is successful but system still shows error of Angular-cli not being installed

https://i.sstatic.net/dINO9.png These are the packages included in my project: "license": "MIT", "dependencies": { "@angular/animations": "^4.0.3", "@angular/common": "^4.0.3", "@angular/compiler": "~4.0.0", "@angular/core": "~4.0.0", ...

Can JavaScript code be utilized within Angular?

Hello, I am wondering if it is acceptable to include JavaScript code within Angular for DOM manipulation purposes. Here is a sample of what I have in mind: document.querySelectorAll('div.links a').forEach(function(item) { const tag = window.lo ...

Displaying data from a service on an Ionic screen: a comprehensive guide

I've retrieved JSON data from an API: { "userGroups":[ {"title":"group 1"}, {"title":"group 2"}, {"title":"group 3"}, {"title":"group 4"} ] } Currently, I am storing this raw data in NativeStorage. // userService this.userGroup ...

Adding an item to a collection using NgRx

I am working with a state that has a specific structure. It consists of a list of Workouts, and each Workout contains a list of exercises associated with it. I have two main objectives: To add new exercises to a particular workout from the existing list o ...

Is it possible to update the Backend IP address after setting up the Angular Frontend and hosting it with nginx?

Our project involves utilizing an Intel NUC with Ubuntu 18.04 for a WebInterface. The backend is up and running on the device, connecting to the frontend through a WebSocket. The front end is powered by Angular and hosted using nginx. However, we've e ...

send image back to Angular component from server response

I'm extremely close to achieving my goal. The server is successfully returning the image and sending it in the response. Now, the challenge lies in getting my angular component to properly display it. Let me share what I have done so far: Firstly, h ...

Utilizing Angular Forms for dynamic string validation with the *ngIf directive

I have a challenge where I need to hide forms in a list if they are empty. These forms contain string values. I attempted to use *ngIf but unfortunately, it did not work as expected and empty fields are still visible in the list. How can I address this iss ...

The sorting feature is not performing as anticipated

I'm dealing with an array of objects fetched from the backend. When mapping and sorting the data in ascending and descending order upon clicking a button, I encountered some issues with the onSort function. The problem lies in the handling of uppercas ...

Managing the closest element depending on the selected option in Angular 5

My task involves accessing the nearest element of a dropdown. The HTML below includes multiple dropdowns and input boxes. When selecting options from the dropdown, I need to enable or disable the input box closest to it. <div class="form-block" *ngFor= ...

Storing my Angular 2 Form information in an SQL database using PHP

Hello everyone! I recently started working with angular and am looking for some guidance. Could someone suggest a tutorial or help me with connecting my angular 2 application to an SQL database using PHP? I'm also interested in learning how to retriev ...

What is the process for printing arrays within JSON objects?

I have implemented a webservice from a Drupal site. { "uid": [ { "value": 8 } ], "uuid": [ { "value": "b823efdc-fa44-45ea-a1f4-a804bae4d215" } ], "langcode": [ { ...

Can you demonstrate how to implement a useState hook as a prop in a component using TypeScript and React?

I have a pair of elements and Currently, I am passing a useState hook from Admin component to Login component as a setAuth prop In my Admin element: const Admin = () => { const [authState, setAuthState] = useState(false); <Login setAuth={set ...

Using Rollup for TypeScript imports with absolute paths

Link to Source Code: https://github.com/arvigeus/roll-on-slow Output Bundle Location: dist Build Log: build.log After bundling with Rollup, warnings are thrown for incorrect source maps (Error when using sourcemap for reporting an error: Can't resolv ...

What is the best way to connect my Angular 2 project to the "$wakanda" service in order to access and retrieve data efficiently?

Recently, I started a new project on the wakanda.io platform using angular2 and backend technologies. After creating some database entities, I now need to retrieve data from the database on the client side. To do this, I am looking for a way to import the ...

The issue with npm modules not appearing in EMCA2015 JS imports persists

I am currently in the process of developing a mobile application with Nativescript using the Microsoft Azure SDK. To get started, I installed the SDK via npm by running this command: $ npm install azure-mobile-apps-client --save However, upon attempting ...

Using JSDoc to Include TypeScript Definitions

I've been attempting to utilize the ts-xor package, which provides a TypeScript definition: export declare type XOR<T, U> = (T | U) extends object ? (Without<T, U> & U) | (Without<U, T> & T) : T | U; This is how I'm imp ...

Automating the process of rewirting git commit messages on a branch using Git

Is there a way to automate the rewriting of commit messages containing a specific substring on a particular branch? For example, in a repository like this: https://i.sstatic.net/3e4bW.png I want to modify all commit messages on the mybranch branch (not o ...

"Visualizing data with Highcharts Map bubbles on a world map centered on the Pacific

Our project requires a map bubble to be displayed on a pacific centered world map. While we have successfully achieved the pacific centered view using information from https://www.highcharts.com/forum/viewtopic.php?t=36545, we are encountering issues whe ...

Navigate using an abstract data type

I am looking to transmit abstract data (In Angular 4 or 5) from one component to another without it being visible in the url. Currently, I am using the following method: let navigationExtras: NavigationExtras = { queryParams: { "firstname": "Nic ...

Is there a more effective way to implement a Custom Validator using .forEach?

I have developed my own validation class as a learning exercise. Do you think this is an effective approach, or do you have suggestions for improvement? import { AbstractControl } from '@angular/forms'; export class ProjectNameValidator { pr ...