Angular 2 does not seem to be acknowledging the custom directive

I developed a unique directive and included it in the setup of my app.module. However, when I try to use it within my component, an error is displayed:

Property binding hasClaim not used by any directive on an embedded template. Ensure that the property name is correctly spelled and all directives are listed in the "@NgModule.declarations".ng

This is the process I followed to create the directive:

import { Directive, TemplateRef, ViewContainerRef, Input } from '@angular/core';
import { SecurityService } from './security.service';

@Directive({
  // tslint:disable-next-line: directive-selector
  selector: '[hasClaim]'
})
export class HasClaimDirective {

  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef,
    private ss: SecurityService,
  ) { }

  @Input() set hasClaim(claimType: any) {
    debugger;
    if (this.ss.hasClaim(claimType)) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
      this.viewContainer.clear();
    }
  }
}

Here is how I implement the directive:

 <ul class="nav">
      <ng-container *ngIf="securityObject.isAuthenticated">
        <li *ngFor="let menuItem of menuItems" routerLinkActive="active" class="{{menuItem.class}}">
            <a [routerLink]="[menuItem.path]" *hasClaim="'Admin'"> <=== THIS IS THE DIRECTIVE
                <i class="nc-icon {{menuItem.icon}}"></i>
                <p>{{menuItem.title}}</p>
            </a>
        </li>
      </ng-container>
      <ng-container *ngIf="!securityObject.isAuthenticated">
        <li routerLinkActive="active" class="">
          <a routerLink="/login">
          <i class="nc-icon nc-key-25"></i>
          <p>Login</p>
        </a>
        </li>
      </ng-container>
      <ng-container *ngIf="securityObject.isAuthenticated">
        <li routerLinkActive="active" class="" (click)="logout()">
          <a routerLink="/login">
          <i class="nc-icon nc-lock-circle-open"></i>
          <p>Logout</p>
        </a>
        </li>
      </ng-container>
    </ul>

https://i.sstatic.net/mv7Sn.png

https://i.sstatic.net/1vZCI.png

Answer №1

One issue you may encounter is when you define the directive in app.module.ts, but intend to use it in a component declared within navBarModule.module.ts

If you only require the directive for the navbar.component, then declare it within the NavBarModule.module instead.

Alternatively, you have the option to create a separate module, such as utils.module, where you can declare and export the directive. Then, import this module in any other modules that contain components requiring the directive.

import { NgModule } from '@angular/core';
import {HasClaimDirective} from './hasclaim.directive'


@NgModule({
  declarations: [ HasClaimDirective ],
  exports:[HasClaimDirective]
})
export class UtilsModule { }

Furthermore, in the nav-module:

@NgModule({
  imports:      [ BrowserModule, FormsModule,UtilsModule ],
  declarations: [ NavBarComponent ],
  exports:[NavBarComponent ]
})
export class NavBarModule { }

Answer №2

Pay close attention to the error message :

The property binding hasClaim is not being used by any directive on an embedded template. Ensure that the property name is spelled correctly and all directives are listed in the "@NgModule.declarations".ng

Solution 1:

Take a look at this line for guidance :

directives are listed in the "@NgModule.declarations"

To fix this issue: navigate to your app.module.ts, import your directive, and then add it to the declarations array after importing.

For instance, in my project I have imported representatives here.

https://i.sstatic.net/JBn5U.png

It seems like the error you're experiencing is suggesting that you should import your directive and add it to the declaration array of app.module.ts

Solution 2:

Avoid using an asterisk (*) before your directive in your HTML code.

As recommended in Angular's documentation, reading this document page might help address your issue.

https://i.sstatic.net/UiIUw.png

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

Creating broken lines with Three.js using BufferGeometry

I find myself in a situation where I need to create a Line with holes, essentially a discontinuous line. This entails my Line being composed of multiple segments that are visually separate but conceptually connected. These segments contain more than just t ...

Guide on obtaining the highest Z-index value from multiple elements using JQuery

Currently tackling a bug that's stumping my senior dev. Here's the issue at hand: In my dashboard, users can drag and drop multiple elements, customizing their placement. However, every time a new element is added, its z-index defaults to ' ...

Leveraging a script within a React component

Trying to implement a payment modal using a js script has led me to suspect that mounting it on the root div causes all components to unmount. I am looking for a way to conditionally load the modal so that users can cancel and open it later. const load ...

Here is a unique version: "Dealing with Node.js ES6 (ESM) Modules in TypeScript can be tricky, especially when the TypeScript Compiler (TSC) fails to emit the

I am facing an issue while transpiling my TypeScript project to JavaScript. I have set the project to resolve as an ES6 Module (ESM) by using the "module":"ES6" configuration, but the problem persists. This is the current setup in my ...

The Canvas element inside a Bootstrap modal is returning inaccurate mouse coordinates

I am currently troubleshooting an issue with a HTML5 canvas inside a Bootstrap modal. The canvas is designed to be a selection game where objects can be selected and manipulated. Everything works fine in the center of the 600x600px canvas, but there is an ...

Retrieving information from a JSON file utilizing an Interface

For the purpose of learning, I am developing a small Ionic app where I want to load data from a JSON file and map it to an interface that defines the data structure. However, I am facing challenges in achieving this: import { Component } from "@angular/co ...

What is the best way for me to bring in this function?

Currently, I am in the process of developing a point-of-sale (POS) system that needs to communicate with the kitchen. My challenge lies in importing the reducer into my express server. Despite multiple attempts, I have been unable to import it either as a ...

Retrieving the Latest State from a Custom React Hook within an Event Listener

I'm encountering a state synchronization issue in a React component involving an event handler and a custom hook. The event handler updates one state variable, and I need to access the most recent value of another state variable that is derived from a ...

Property initialization status not being inherited by class

I'm encountering a situation where the properties of the base class are not being recognized as initialized in the extended class when I inherit a class. I'm unsure if this is a TypeScript or TSLint issue, as my Google search didn't yield re ...

Is it acceptable to add customized (personalized) properties to DOM objects?

<div id="customDiv"></div> document.getElementByid('customDiv').myAttribute='customValue'; if('undefined'!==typeof document.getElementById('customDiv').myAttribute){ Would it be acceptable and compatib ...

Adding a collection of items to an array in preparation for organizing

Realizing that sorting objects is not feasible - despite the necessity of having the object values sorted - I conclude that the only option is to move the object array content into a new array for sorting purposes. The following code generates the output ...

Issue with Node.js MongoDB collection.find().toArray not returning results

Despite coming across questions similar to mine, I struggled to resolve the issue independently. Within my '../models/user' model, my goal is to retrieve all users and store them in an array, which will then be returned to the controller for fur ...

What is the best way to obtain the true dimensions of an HTML element?

Is there a way to determine the dimensions of a <div> element in order to accurately position it at the center of the browser window? Additionally, which browsers are compatible with this method? ...

What are the steps to incorporate SVG into a React Native project?

I'm in the process of integrating bootstrap icons into my react native project, but I've been having trouble finding clear instructions on how to render an SVG in react-native. Can anyone provide some guidance on this? ...

Exploring ways to locate a specific text within a URL using nodeJS

Here is a simple code snippet with a problem to solve: var S = require('string'); function checkBlacklist(inputString) { var blacklist = ["facebook", "wikipedia", "search.ch", "local.ch"]; var found = false; for (var i = 0; i < b ...

Tips for providing arguments in the command line to execute a yarn script

Just starting out with JavaScript. I understand that npm allows for passing variables in the command line using process.env.npm_config_key like this: npm run --key="My Secret Passphrase" test:integration How can I achieve the same thing with yarn? I&apo ...

How can I disable the automatic generation of index paths from embedded documents in mongoose?

It appears that mongoose is automatically generating indexes for embedded documents. Is there a setting to disable the automatic index creation feature? For instance, the code snippet https://github.com/Automattic/mongoose/blob/master/lib/schema.js#L940 s ...

The Material-ui Drawer does not function properly when used with an external CSS file

For my project, I'm working on a Sidebar design that is inspired by the Mini Variant drawer demo available at this link. However, the project requirements mandate that all CSS styling should be done in a separate CSS file rather than directly within t ...

"Angular2: The Mysterious Disappearance of the Router

I'm facing an issue with defining a redirect from my login to the dashboard after successfully verifying a user. When I try to implement "this.router.navigate(['/dashboard'])" in my login component, I encounter the following error: "excepti ...

Acquiring MySQL information and storing it in a variable array

Currently, I am retrieving data from MySQL with $username and $chance. The data contains two usernames but only the first one is being loaded. var data = [ { "name" : "<?php echo $username; ?>", "hvalue" : <?php echo $chan ...